/*************************************************************************
> File Name: 2.100_child.c
> Author: suyelu
> Mail: suyelu@126.com
> Created Time: Sat 17 Oct 2020 03:05:43 PM CST
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int x;
for (int i = 1; i <= 100; i++) {
x = i;
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
break;
}
}
if (pid == 0) {
printf("I'm %dth Child!\n", x);
sleep(1);
} else {
for (int i = 1; i <= 100; i++) {
int wstatus;
pid_t rpid = wait(&wstatus);
printf("Child %d returns with code %d\n", rpid, wstatus);
}
pid_t tmp = wait(NULL);
printf("%d\n", tmp);
}
return 0;
}
/*************************************************************************
> File Name: 3.exec.c
> Author: suyelu
> Mail: suyelu@126.com
> Created Time: Sat 17 Oct 2020 04:55:30 PM CST
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
pid_t pid;
if ((pid = fork()) < 0) {
perror("fork()");
exit(1);
}
if (pid == 0) {
printf("I'm Child!\nI'm do a great job now!\n");
execlp("cat", "cat", "3.exec.c", NULL);
printf("I'm si le!\n");
} else {
printf("I'm Father!\n");
wait(NULL);
}
return 0;
}
/*************************************************************************
> File Name: 4.my_exec.c
> Author: suyelu
> Mail: suyelu@126.com
> Created Time: Sat 17 Oct 2020 06:44:49 PM CST
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int opt;
int m_flag = 0;
char msg[512] = {0};
while ((opt = getopt(argc, argv, "m:")) != -1) {
switch (opt) {
case 'm':
printf("have m!\n");
m_flag = 1;
strcpy(msg, optarg);
break;
default:
fprintf(stderr, "Usage : %s -m msg\n", argv[0]);
exit(1);
}
}
if (m_flag == 1) {
printf("msg = %s\n", msg);
return 0;
}
pid_t pid;
if ((pid = fork()) < 0) {
perror("fork()");
exit(1);
}
if (pid == 0) {
// vim
printf("We will open a Vim!\n");
sleep(1);
execl("/usr/bin/vim", "vim", "tmp.txt", NULL);
} else {
pid_t pid1;
wait(NULL);
printf("Vim is Out!\n");
if ((pid1 = fork()) < 0) {
perror("fork()");
exit(1);
}
if (pid1 == 0) {
sleep(1);
printf("Cat will be do!\n");
sleep(1);
execlp("cat", "cat", "tmp.txt", NULL);
} else {
wait(NULL);
printf("Cat is Over!\n Delete tmp.txt in 2s!\n");
sleep(1);
execlp("rm", "rm", "./tmp.txt", NULL);
}
//exec
}
return 0;
}
linux: 使用多进程,编写简单命令my_exec
最新推荐文章于 2024-09-21 16:02:20 发布
本文通过三个示例程序详细介绍了Linux系统中进程创建(fork)和程序执行(exec)的基本用法。示例涵盖了简单进程创建、子进程执行外部程序以及多个进程协作完成任务的场景。涉及的关键技术包括wait、execlp等函数的使用。
摘要由CSDN通过智能技术生成