在Linux系统中编写 C程序,创建一个子进程。父进程和子进程交替运行。父进程先显示一次“Current time:”,

2025-06-28 10:37:24
推荐回答(2个)
回答1:

#include
#include
#include
#include
#include

int main(int argc, char *argv[]) {
int status;
pid_t pid;
pid_t subpid;
pid=fork();
if(pid > 0) {
while(1) {
fprintf(stdout, "parent process working ... \n");
sleep(1);
}
}else if(pid == 0) {
while(1) {
subpid=getpid();
sleep(1);
fprintf(stdout, "child process working ... \n");
}
}else if(pid == -1) {
fprintf(stderr, "%s: create subprocess failed. pid=%d\n",
__func__, getpid());
}
}
自己编译试试?

回答2:

先创建一个母进程,母进程跟父进程交叉运行,过会就蹦出,那就安居乐业了。