Linux中通过fork()同时创建多个进程

1、使用系统调用fork()创建三个子进程;

2、各个子进程显示和输出一些提示信息和自己的进程标识符;

3、父进程显示自己的进程ID和一些提示信息,然后调用waitpid()等待多个子进程结束,并在子进程结束后显示输出提示信息表示程序结束。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>

int tprintf(const char *fmt,...);

int main(void)
{
	printf("I'm your father,PID is %d.\n",getpid());
	pid_t pid = fork();
	if(pid == 0){
		printf("I'm a first son.PID is %d.\n",getpid());
		exit(1);//若此处没有exit(1), 进程也会执行 pid_t pid2 = fork()语句,会出现孙进程
		printf("You should never see this.\n");
	}
	pid_t pid2 = fork();
	if(pid2 == 0){
		printf("I'm a second son.PID is %d.\n",getpid());
		exit(1);
		printf("You should never see this.\n");
	}
	pid_t pid3 = fork();
	if(pid3 ==0){
		printf("I'm a third son.PID is %d.\n",getpid());
		exit(1);
		printf("You should never see this.\n");
	}
	else if(pid != -1){
		tprintf("Parent forked child process--%d.\n",pid);
		tprintf("Parent is waiting for child to exit.\n");
		waitpid(pid,NULL,0);
		waitpid(pid2,NULL,0);
		waitpid(pid3,NULL,0);
		tprintf("Child Process had exited.\n");
		tprintf("Parent had exited.\n");
	}
	else	tprintf("Everything was done without error.\n");

	return 0;
}


/*
* 设置输出格式
*/
int tprintf(const char* fmt,...)
{
	va_list args;
	struct tm *tstruct;
	time_t tsec;
	tsec = time(NULL);
	tstruct = localtime(&tsec);
	printf("%02d:%02d:%02d:%5d|",tstruct->tm_hour,tstruct->tm_min,tstruct->tm_sec,getpid());
	va_start(args,fmt);
	return vprintf(fmt,args);
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值