C进程间通信

时间:2013-05-15 15:47:06

标签: c fork ipc pipe execvp

我正在尝试编写一个程序,它接受n个进程并将每个父进程的输出传递给子进程的输入。

我想问题在于关闭管道。

输入的一个例子是:./a.out“ps ufax”“grep color”“sort -n” 预期产量: colord 2013 0.0 0.1 279216 4580? Sl 08:01 0:00 / usr / lib / x86_64-linux-gnu / colord / colord zabsa90 2525 0.0 0.0 9392 920 pts / 2 S + 08:26 0:00 _ grep color

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include "log.h"

#define PROGRAM_NAME    "IPC.log"

void parse( int position ,char *argv[] ,char *commands ,char *argument[]) ;

void handler(int sig) {
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, 2);
    exit(1);
}
int main(int argc ,char * argv[])
{
signal(SIGSEGV, handler);
 if (argc == 1) 
  { printf("Errore. Inserire almeno un argomento per il corretto funzionamento. Esempio: %s pwd\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  int number_process = argc-1; 
  int pipe_number = argc*2;
  int pfd[pipe_number];
  char  command[30];
  char *argument[1040];
  int child = 0;
  int parent = 0;
  int count =0;
  int pid ;


 argc--;
 while(child < number_process && parent < 1) 
  {
     pipe(pfd+count);
     pid=fork();

     if ( pid == 0 )
       {
         // close(pfd[count] ); 
         dup2(pfd[count+1], 1 ); 
         count +=2;
         parent ++; 
         argc--;
       }
     else
       { 
         parent++;
         wait(&pid);

         //  close( pfd[count+1] );
         dup2( pfd[count], 0 );
         parse( argc, argv ,command ,argument);
         // execvp(commands,argument);
        }
   }

     return 0;
}

void parse(int position ,char *argv[] ,char *command ,char *argument[] )    // parse the command line : store the command in a String and the 
                                                                             // and the arguments in array string
 {
    char *result = NULL ;
    char buffer [30] ;
    int count =0;

     strcpy(buffer,argv[position]);
     result =strtok(buffer," ");
     strcpy(command,result); 

     while(result !=NULL )
      {
        argument[count] =result ;
        result=strtok(NULL," ");
        count++;

      }
   execvp(command,argument);

 } 

谢谢:)

0 个答案:

没有答案
相关问题