LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 709|回复: 1

如何让子进程实现一个一个的输出

[复制链接]
发表于 2007-6-13 21:20:25 | 显示全部楼层 |阅读模式
我 有一个 程序,是想让五个子进程一个一个地打印出信息,但是程序实现的是五个进程一起打印出来了,怎么改才能实现呢? 麻烦给看看

#include "stdio.h"
#include <sys/types.h>
#include <unistd.h>
#include <sched.h>
#include <signal.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>

pid_t pid[5];
void kill_process()
{
exit(0);
}

/*显示进程调度策略和优先级的信息*/
void show_info(pid_t pid)
{
struct sched_param sp;
int policy;

policy = sched_getscheduler(pid);
if (policy == -1) {
perror("sched_getscheduler");
fprintf(stderr, "failed to get pid %d's policy\n", pid);
exit(1);
}

printf("scheduling policy: ");/*打印进程的调度策略*/
switch (policy) {
case SCHED_OTHER:
printf("SCHED_OTHER\n");
break;
case SCHED_FIFO:
printf("SCHED_FIFO\n");
break;
case SCHED_RR:
printf("SCHED_RR\n");
break;
default:
printf("unknown\n");
}

if (sched_getparam(pid, &sp)) {
perror("sched_getparam");
fprintf(stderr, "failed to get pid %d's attributes\n", pid);
exit(1);
}

printf("scheduling priority: %d\n", sp.sched_priority);/*打印进程的优先级*/
}


void user_fork(int i)
{
char outstr[20];

if ((pid = fork()) < 0) { /*创建进程*/
printf("fork error");
}
else if (pid == 0) {
signal(SIGUSR1,kill_process);
while(1)
{
sleep(10);
sprintf(outstr,"I am P%d---pid=%d\n",i+1,getpid());
write(1,outstr,sizeof(outstr));
strcpy(outstr,"");
pid=getpid();
show_info(pid);

}

}
}


int
main(void)
{
pid_t pid[5];
user_fork(0);
sleep(10);
user_fork(1);
sleep(10);
user_fork(2);
sleep(10);
user_fork(3);
sleep(10);
kill(pid[3],SIGUSR1);
kill(pid[2],SIGUSR1);
user_fork(4);
sleep(10);
if(waitpid(pid[3],NULL,0)!=pid[3])
write(2,"wait 3 error",20);
if(waitpid(pid[2],NULL,0)!=pid[2])
write(2,"wait 2 error",20);
getchar();
exit(0);

}
发表于 2007-6-15 11:22:44 | 显示全部楼层
把子进程拥塞,某一子进程打印完了之后再唤醒接下来的子进程!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表