|
我 有一个 程序,是想让五个子进程一个一个地打印出信息,但是程序实现的是五个进程一起打印出来了,怎么改才能实现呢? 麻烦给看看
#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);
} |
|