#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
int status;
pid_t pid = fork();
if(-1 == pid){
perror("Fork Error");
}else if (0 == pid ){
strcpy(argv[0], "pid child process");
setsid();
while(1){
printf("Hello world\n");
sleep(5);
}
}else{
strcpy(argv[0], "pid parent process");
printf("the child pid is %d\n", wait(&status));
exit(0);
}
}
[b][color=blue]gcc -o pid pid.c
./pid
exit
ps aux | grep pid
kill -9 [/color][/b]

本文提供了一个使用C语言实现的简单父子进程示例。通过fork()创建子进程,并展示了如何在子进程中运行无限循环输出“Hello World”,同时父进程等待子进程结束并输出子进程ID。
63

被折叠的 条评论
为什么被折叠?



