把刚才的程序用C语言写一遍
时间: 2023-10-02 17:04:25 浏览: 54
好的,以下是使用 C 语言实现的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid1, pid2;
int status;
// 创建第一个子进程
pid1 = fork();
if (pid1 == 0) {
// 子进程1运行命令后退出
system("echo 'Child process 1'");
exit(0);
} else {
// 父进程阻塞等待子进程1结束
waitpid(pid1, &status, 0);
printf("Child process 1 exited with status %d\n", status);
// 创建第二个子进程
pid2 = fork();
if (pid2 == 0) {
// 子进程2运行ps命令后等待5秒退出
system("ps");
sleep(5);
exit(0);
} else {
// 父进程非阻塞等待子进程2结束
while (1) {
int result = waitpid(pid2, &status, WNOHANG);
if (result == pid2) {
printf("Child process 2 exited with status %d\n", status);
break;
} else {
printf("Waiting for child process 2 to finish...\n");
sleep(1);
}
}
}
}
return 0;
}
```
该程序与 Python 版本的程序类似,使用了 `fork()` 函数创建子进程,使用了 `system()` 函数运行命令,使用了 `waitpid()` 函数等待子进程结束,并使用了 `WNOHANG` 标志实现非阻塞等待。需要注意的是,C 语言中的 `exit()` 函数需要传入退出码,因此在程序中我们传入了 0 表示正常退出。