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

41 lines
914 B
C
Raw Permalink 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.

// 请分析如下程序如何实现创建2个子进程 第一个子进程输出ABC, 第二子进程输出 DEF。
// 做法二
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h> // atexit
void clearAll1()
{
printf("%d 清退资源1...\n", getpid());
}
void clearAll2()
{
printf("%d 清退资源2...\n", getpid());
}
int main(int argc, char *argv[])
{
atexit(clearAll1); // 清退,退出前执行
atexit(clearAll2);
int pid = fork();
if (pid == 0)
{
sleep(5);
printf("%d 子进程结束\n", getpid());
// atexit(clearAll); // 清退,退出前执行,子进程无法清退
_exit(1);
}
else if (pid > 0)
{
// atexit(clearAll); // 清退,退出前执行
wait(NULL); // 等待子进程
printf("主进程 %d 结束\n", getpid());
}
return 0;
}