當前位置:編程學習大全網 - 編程語言 - linux系統編程 壹個基於管道的通信環

linux系統編程 壹個基於管道的通信環

下面是修改後的代碼:

主要的問題:

1 pipe返回的壹對描述符,如果自己只用了寫,那麽把讀關掉,而不是都關掉。

2 strtok的用法不對

3 打印信息有誤導,send和receive沒有列寫清楚。

#include <errno.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <time.h>

int main(int argc,char *argv[])

{

pid_t childpid;

int error;

int fd[2];

int i;

int nprocs;

long num1,num2;

char mybuf[512]={0};

char *bp = mybuf;

int a,b,c;

int n;

if((argc!=2)||((nprocs=atoi(argv[1]))<=0)){

fprintf(stderr,"Usage:%s nprocs\n",argv[0]);

return 1;

}

if(pipe(fd) == -1){

perror("Failed to create starting pipe");

return 1;

}

if((dup2(fd[0],STDIN_FILENO) == -1) || (dup2(fd[1],STDOUT_FILENO) == -1)){

perror("Failed to conect pipe");

return 1;

}

for(i=1;i<nprocs;i++){

if(pipe(fd) == -1){

fprintf(stderr,"[%ld]:failed to create pipe %d: %s\n",(long)getpid(),i,strerror(errno));

return 1;

}

if((childpid = fork()) == -1){

fprintf(stderr,"[%ld]:failed to creat a child %d: %s\n",(long)getpid(),i,strerror(errno));

return 1;

}

if(childpid>0) {

error=dup2(fd[1],STDOUT_FILENO);

close(fd[0]);

}

else {

error=dup2(fd[0],STDIN_FILENO);

close(fd[1]);

}

if(error == -1){

fprintf(stderr,"[%ld]:failed to dup pipes for iteration %d %s\n",(long)getpid(),i,strerror(errno));

return 1;

}

if(childpid)

break;

}

if(i == 1)

{

a = 1;

b = 1;

sprintf(mybuf,"%d:%d",a,b);

write(STDOUT_FILENO,mybuf,strlen(mybuf)+1);

fprintf(stderr,"This is id:%d with pid:%d parent pid:%d send:%s\n",

i,getpid(),getppid(),mybuf);

read(STDIN_FILENO,mybuf,32);

fprintf(stderr,"This is id:%d with pid:%d parent pid:%d received:%s\n",

i,getpid(),getppid(),mybuf);

}

else if(read(STDIN_FILENO,mybuf,32) != -1)

{

fprintf(stderr,"This is id:%d with pid:%d parent pid:%d received:%s\n",

i,getpid(),getppid(),mybuf);

a = atoi(strtok(mybuf, ":"));

b = atoi(strtok(NULL, ":"));

c = a + b;

fprintf(stderr,"This is id:%d with pid:%d key:%d:%d\n",i,getpid(), a, b);

sprintf(mybuf,"%d:%d",b,c);

write(STDOUT_FILENO,mybuf,strlen(mybuf)+1);

fprintf(stderr,"This is id:%d with pid:%d parent pid:%d send:%s\n",

i,getpid(),getppid(),mybuf);

}

wait(NULL);

return 0;

}

  • 上一篇:FANUC系統和西門子系統的區別?指令有什麽不同?
  • 下一篇:VPS和虛擬主機有什麽區別?
  • copyright 2024編程學習大全網