#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
char *message;
int n;
printf("fork program starting");
pid=fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message="This is the child";
n=5;
break;
default:
message="This is the parent";
n=3;
break;
}
for(;n>0;n--)
{
puts(message);
sleep(1);
}
exit(0);
}
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
char *message;
int n;
printf("fork program starting");
pid=fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message="This is the child";
n=5;
break;
default:
message="This is the parent";
n=3;
break;
}
for(;n>0;n--)
{
puts(message);
sleep(1);
}
exit(0);
}
本文通过一个C语言示例程序介绍了如何使用fork()函数创建子进程,并展示了父进程与子进程之间的基本交互方式。该程序实现了根据进程类型(父进程或子进程)输出特定信息的功能,并通过循环重复输出,利用sleep()函数模拟了简单的延时。
1696

被折叠的 条评论
为什么被折叠?



