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

48 lines
982 B
C

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <string.h>
void show(int n)
{
for (int i = 0; i < n; i++)
{
// printf("%d 进程 -> %d\n", getpid(), i);
char buf[32];
sprintf(buf, "%d 进程 -> %d\n", getpid(), i);
/*
#define STDIN_FILENO 0 // Standard input.
#define STDOUT_FILENO 1 // Standard output.
#define STDERR_FILENO 2 // Standard error output.
*/
write(STDOUT_FILENO, buf, strlen(buf));
sleep(1);
}
}
int main()
{
for (int i = 0; i < 5; i++)
{
int pid = fork();
if (pid == 0)
{
show(i + 1);
_exit(0);
}
}
while (1)
{
int status;
int pid = waitpid(0, &status, WUNTRACED);
if (pid == -1)
{
break;
}
printf("%d 子进程结束\n", pid);
}
return 0;
}