qfedu-linux-advanced-level/day3/d5.c

36 lines
724 B
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h> // atexit
#include <fcntl.h>
int main(int argc, char const *argv[])
{
// vfork 子进程和父进程会共享内存
pid_t pid = vfork();
if (pid == 0)
{
// 子进程
for (int i = 0; i < 5; i++)
{
printf("%d vfork的子进程 i=%d\n", getpid(), i);
sleep(1);
}
_exit(0); // 回收资源退出; vfork创建的子进程结束后才会执行父进程
}
else if (pid > 0)
{
// 父进程
while (1)
{
printf("%d 父进程 \n", getpid());
sleep(1);
}
}
return 0;
}