Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 父级如何在每个子级和自身之间创建管道,以及每个子级如何通过管道向父级发送字数_C_Operating System_Filesystems_Pipe_Fork - Fatal编程技术网

C 父级如何在每个子级和自身之间创建管道,以及每个子级如何通过管道向父级发送字数

C 父级如何在每个子级和自身之间创建管道,以及每个子级如何通过管道向父级发送字数,c,operating-system,filesystems,pipe,fork,C,Operating System,Filesystems,Pipe,Fork,我编写的代码通过创建多个进程来计算多个文本文件中的字数,每个进程负责一个文件来计算字数 我想做的是使用管道找出所有文件中的总字数 因此,家长应: 在每个子级和它自身之间创建一个管道,以便它可以从每个子级获取字数 通过添加通过管道接收的数字,报告所有文件中的总字数 检查每个子项的退出状态并打印出该子项如何退出 退出 也让每个孩子: 通过管道将字数发送给父级 如果文件没有,则通过管道将0作为字数发送到父级 不存在或发生任何其他错误 如果成功打开文件并返回,则返回/退出0 计算该文件中的字数,如

我编写的代码通过创建多个进程来计算多个文本文件中的字数,每个进程负责一个文件来计算字数

我想做的是使用管道找出所有文件中的总字数

因此,家长应:

  • 在每个子级和它自身之间创建一个管道,以便它可以从每个子级获取字数

  • 通过添加通过管道接收的数字,报告所有文件中的总字数

  • 检查每个子项的退出状态并打印出该子项如何退出 退出

  • 也让每个孩子:

  • 通过管道将字数发送给父级
  • 如果文件没有,则通过管道将0作为字数发送到父级 不存在或发生任何其他错误
  • 如果成功打开文件并返回,则返回/退出0 计算该文件中的字数,如果存在 错误(例如,文件不存在等)
  • #包括
    #包括
    #包括
    #包括
    #定义最大字符100
    pid_t getpid(无效);
    pid_t getppid(无效);
    字符*itoa(整数i,字符b[]{
    字符常量数字[]=“0123456789”;
    char*p=b;
    如果(i=0){
    printf(“用于%s的子进程pid\ud:字数为%d\n”,i,arvg[i],字);
    //我不知道如何在管道中写入int,因此下面可能是错误的
    书写(*书写单词,1);
    返回0;
    }else if(单词==-1){
    printf(“用于%s的子进程pid_u%d:不存在”\n“,i,arvg[i]);
    //我不知道如何在管道中写入int,因此下面可能是错误的
    书写(标准文件号,单词,1);
    出口(1);
    }
    }否则{
    关闭(*write_fd);
    //我不知道如何从管道中读取int
    read(*read_fd和readbuffer,1);
    totalwords+=???
    关闭(*read_fd);
    //等待所有子进程退出/返回
    如果(ppid==getpid()){
    等待(&状态);
    }
    //检查它们的退出代码,WEXITSTATUS=子级退出时返回代码
    if(WEXITSTATUS(status)==1){
    计数++;
    }
    }
    }
    printf(“主进程创建了%d个子进程来计算%d个文件中的字\n”,argc-1,argc-1);
    printf(“总字数为%d”,总字数);
    printf(“%d个文件已成功计数!\n”,argc-1-count);
    printf(“%d个文件不存在。\n”,计数);
    返回0;
    }```
    有人能帮我弄清楚吗?我真的不知道如何用烟斗达到我的目标。
    
    发现代码存在一些问题。我为你修好了它们(不过,我会做同样的事情,稍微有点不同)

  • 从管道中读取和写入int非常简单,只是在读取或写入int时正确地键入

  • 不需要将malloc转换为pid。另外,malloc返回一个指针,并且应该使用(int*)进行类型转换

  • 在使用调用时始终添加正确的包含。手动页面或阅读有关调用的信息,同时尝试理解传递的参数和返回值是非常有用的

  • 说够了,这是你的工作代码

    
        #include <stdio.h>
        #include <stdlib.h>
        #include <sys/types.h>
        #include <unistd.h>
        #include <sys/wait.h>
        
        #define MAX_CHAR 100
        
        pid_t getpid(void);
        pid_t getppid(void);
        
        char* itoa(int i, char b[]){
            char const digit[] = "0123456789";
            char* p = b;
            if(i<0){
                *p++ = '-';
                i *= -1;
            }
            int shifter = i;
            do{ //Move to where representation ends
                ++p;
                shifter = shifter/10;
            }while(shifter);
            *p = '\0';
            do{ //Move back, inserting digits as u go
                *--p = digit[i%10];
                i = i/10;
            }while(i);
            return b;
        }
        int countWords(char * fp, int pid) {
           FILE * file;
           int words = 0;
           char word[MAX_CHAR];
           //execute this function only if child process of parent, no gradchild is allowed to execute this function!
           if (pid == getppid()) {
              file = fopen(fp, "r");
              if (file == NULL) {
                 return -1;
              }
              //find string in the file and count the words.
              while (fscanf(file, "%s", word) != EOF) {
                 words++;
              }
              return words;
           } else {
              return -1;
           }
           return 0;
        }
        
        int main(int argc, char * arvg[]) {
           //if invalid arguments
           if (argc < 2) {
              fprintf(stderr, "ERROR: INVALID ARGUMENTS");
              exit(-1);
           }
        
           int count = 0, pid, ppid, status, totalwords = 0;
           
           int result = -1;
           int fd[2];
           char string[100];
           char readbuffer[80];
           int *write_fd = &fd[1];
           int *read_fd = &fd[0];
           int recvd = 0;
           result = pipe(fd);
           if(-1 == result){
             perror("pipe");
             return -1;
           }
           //creates (argc - 1) child processes using fork()
           //pid = (int) malloc((argc - 1) * sizeof(int));
           //parent pid
           ppid = getpid();
        
           //each child process to count the number of words in each file
           for (int i = 1; i < argc; i++) {
              //child process
              pid = fork();
              if( pid == -1){
                  perror("failed to fork");
                  return -1;
              }else if (pid == 0) {
                  printf ("%d child running \n", i);
                 // call a function to count the number of words in file arvg[i]
                 int words = countWords(arvg[i], ppid);
                 close(*read_fd);
                 if (words >= 0) {
                    printf("Child process pid_%d for %s :number of words is %d\n", i, arvg[i], words);
                    //I don't know how to write int into the pipe,so below might be wrong
                    write(*write_fd, (void *)&words, 1);
                  
                    return 0;
                 } else if (words == -1) {
                    printf("Child process pid_%d for %s :does not exists\n", i, arvg[i]);
                    //I don't know how to write int into the pipe,so below might be wrong
                    write(STDOUT_FILENO, (void *)&words, 1);
                    
                    exit(1);
                 }
              } else {
                 close(*write_fd);
        
                 //and I have no idea how to read int from pipes
                 read(*read_fd, (void*)&recvd, 1);
        
                 totalwords += recvd;
                 printf("recvd %d \n", totalwords);
                 close(*read_fd);
                 //Wait until all child processes exit/return
                 if (ppid == getpid()) {
                    wait( & status);
                 }
                 //inspect their exit codes, WEXITSTATUS = return code when child exits
                 if (WEXITSTATUS(status) == 1) {
                    count++;
                 }
              }
           }
           printf("Main process created %d child processes to count words in %d files\n", argc - 1, argc - 1);
           printf("Total words is %d\n", totalwords);
           printf("%d files have been counted sucessfully!\n", argc - 1 - count);
           printf("%d files did not exist.\n", count);
        
           return 0;
        }
    
    
    
    #包括
    #包括
    #包括
    #包括
    #包括
    #定义最大字符100
    pid_t getpid(无效);
    pid_t getppid(无效);
    字符*itoa(整数i,字符b[]{
    字符常量数字[]=“0123456789”;
    char*p=b;
    如果(i=0){
    printf(“用于%s的子进程pid\ud:字数为%d\n”,i,arvg[i],字);
    //我不知道如何在管道中写入int,因此下面可能是错误的
    书写(*书写(无效*)和文字,1);
    返回0;
    }else if(单词==-1){
    printf(“用于%s的子进程pid_u%d:不存在”\n“,i,arvg[i]);
    //我不知道如何在管道中写入int,因此下面可能是错误的
    书写(标准文件号(void*)和单词,1);
    出口(1);
    }
    }否则{
    关闭(*write_fd);
    //我不知道如何从管道中读取int
    read(*read_fd,(void*)和recvd,1);
    totalwords+=recvd;
    printf(“记录%d\n”,totalwords);
    关闭(*read_fd);
    //等待所有子进程退出/返回
    如果(ppid==getpid()){
    等待(&状态);
    }
    //检查它们的退出代码,WEXITSTATUS=子级退出时返回代码
    if(WEXITSTATUS(status)==1){
    计数++;
    }
    }
    }
    printf(“主进程创建了%d个子进程来计算%d个文件中的字\n”,argc-1,argc-1);
    printf(“总字数为%d\n”,总字数);
    printf(“%d个文件已成功计数!\n”,argc-1-count);
    printf(“%d个文件不存在。\n”,计数);
    返回0;
    }
    
    发现代码存在一些问题。我为你修好了它们(不过,我会做同样的事情,稍微有点不同)

  • 从管道中读取和写入int非常简单,只是在读取或写入int时正确地键入

  • 不需要将malloc转换为pid。另外,malloc返回一个指针,并且应该使用(int*)进行类型转换

  • 在使用调用时始终添加正确的包含。手动页面或阅读有关调用的信息,同时尝试理解传递的参数和返回值是非常有用的

  • 说够了,这是你的工作代码

    
        #include <stdio.h>
        #include <stdlib.h>
        #include <sys/types.h>
        #include <unistd.h>
        #include <sys/wait.h>
        
        #define MAX_CHAR 100
        
        pid_t getpid(void);
        pid_t getppid(void);
        
        char* itoa(int i, char b[]){
            char const digit[] = "0123456789";
            char* p = b;
            if(i<0){
                *p++ = '-';
                i *= -1;
            }
            int shifter = i;
            do{ //Move to where representation ends
                ++p;
                shifter = shifter/10;
            }while(shifter);
            *p = '\0';
            do{ //Move back, inserting digits as u go
                *--p = digit[i%10];
                i = i/10;
            }while(i);
            return b;
        }
        int countWords(char * fp, int pid) {
           FILE * file;
           int words = 0;
           char word[MAX_CHAR];
           //execute this function only if child process of parent, no gradchild is allowed to execute this function!
           if (pid == getppid()) {
              file = fopen(fp, "r");
              if (file == NULL) {
                 return -1;
              }
              //find string in the file and count the words.
              while (fscanf(file, "%s", word) != EOF) {
                 words++;
              }
              return words;
           } else {
              return -1;
           }
           return 0;
        }
        
        int main(int argc, char * arvg[]) {
           //if invalid arguments
           if (argc < 2) {
              fprintf(stderr, "ERROR: INVALID ARGUMENTS");
              exit(-1);
           }
        
           int count = 0, pid, ppid, status, totalwords = 0;
           
           int result = -1;
           int fd[2];
           char string[100];
           char readbuffer[80];
           int *write_fd = &fd[1];
           int *read_fd = &fd[0];
           int recvd = 0;
           result = pipe(fd);
           if(-1 == result){
             perror("pipe");
             return -1;
           }
           //creates (argc - 1) child processes using fork()
           //pid = (int) malloc((argc - 1) * sizeof(int));
           //parent pid
           ppid = getpid();
        
           //each child process to count the number of words in each file
           for (int i = 1; i < argc; i++) {
              //child process
              pid = fork();
              if( pid == -1){
                  perror("failed to fork");
                  return -1;
              }else if (pid == 0) {
                  printf ("%d child running \n", i);
                 // call a function to count the number of words in file arvg[i]
                 int words = countWords(arvg[i], ppid);
                 close(*read_fd);
                 if (words >= 0) {
                    printf("Child process pid_%d for %s :number of words is %d\n", i, arvg[i], words);
                    //I don't know how to write int into the pipe,so below might be wrong
                    write(*write_fd, (void *)&words, 1);
                  
                    return 0;
                 } else if (words == -1) {
                    printf("Child process pid_%d for %s :does not exists\n", i, arvg[i]);
                    //I don't know how to write int into the pipe,so below might be wrong
                    write(STDOUT_FILENO, (void *)&words, 1);
                    
                    exit(1);
                 }
              } else {
                 close(*write_fd);
        
                 //and I have no idea how to read int from pipes
                 read(*read_fd, (void*)&recvd, 1);
        
                 totalwords += recvd;
                 printf("recvd %d \n", totalwords);
                 close(*read_fd);
                 //Wait until all child processes exit/return
                 if (ppid == getpid()) {
                    wait( & status);
                 }
                 //inspect their exit codes, WEXITSTATUS = return code when child exits
                 if (WEXITSTATUS(status) == 1) {
                    count++;
                 }
              }
           }
           printf("Main process created %d child processes to count words in %d files\n", argc - 1, argc - 1);
           printf("Total words is %d\n", totalwords);
           printf("%d files have been counted sucessfully!\n", argc - 1 - count);
           printf("%d files did not exist.\n", count);
        
           return 0;
        }
    
    
    
    #包括
    #包括
    #包括
    #包括
    #包括
    #定义最大字符100
    pid_t getpid(无效);
    pid_t getppid(无效);
    
    
        #include <stdio.h>
        #include <stdlib.h>
        #include <sys/types.h>
        #include <unistd.h>
        #include <sys/wait.h>
        
        #define MAX_CHAR 100
        
        pid_t getpid(void);
        pid_t getppid(void);
        
        char* itoa(int i, char b[]){
            char const digit[] = "0123456789";
            char* p = b;
            if(i<0){
                *p++ = '-';
                i *= -1;
            }
            int shifter = i;
            do{ //Move to where representation ends
                ++p;
                shifter = shifter/10;
            }while(shifter);
            *p = '\0';
            do{ //Move back, inserting digits as u go
                *--p = digit[i%10];
                i = i/10;
            }while(i);
            return b;
        }
        
        // count word from file provided
        int countWords(char * fp, int pid) {
           FILE * file;
           int words = 0;
           char word[MAX_CHAR];
           //execute this function only if child process of parent, no gradchild is allowed to execute this function!
           if (pid == getppid()) {
              file = fopen(fp, "r");
              if (file == NULL) {
                 return -1;
              }
              //find string in the file and count the words.
              while (fscanf(file, "%s", word) != EOF) {
                 words++;
              }
              return words;
           } else {
              return -1;
           }
           return 0;
        }
        
        //do everything related to child here in this function
        void child_process(int write_fd, char *filename, int ppid)
        {
            // call a function to count the number of words in file argv[i]
            printf("counting words of %s\n", filename);
            int words = countWords(filename, ppid);
            if (words >= 0) {
                printf("Child process pid for %s :number of words is %d\n", filename, words);
                write(write_fd, (void *)&words, 1);
                close(write_fd);
                exit(0);
            } else if (words == -1) {
                printf("Child process pid for %s :does not exist\n", filename);
                write(STDOUT_FILENO, (void *)&words, 1);
                close(write_fd);
                exit(1);
            }
            return;
        }
        
        int main(int argc, char * argv[]) {
           //if invalid arguments
           if (argc < 2) {
              fprintf(stderr, "ERROR: INVALID ARGUMENTS");
              exit(-1);
           }
        
           int pid = 0;
           int ppid = 0;
           int totalwords = 0;
           int fd[2] = {0};
           int write_fd = 0;
           int read_fd = 0;
           int recvd = 0;
        
           // open a pipe
           if(-1 == pipe(fd)){
             perror("pipe");
             return -1;
           }
        
           // assign write_fd and read_fd
           write_fd = fd[1];
           read_fd = fd[0];
        
           //parent pid
           ppid = getpid();
        
           //each child process to count the number of words in each file
           pid = fork();
           for (int i = 0; i < argc-1; i++)
           {
               //child process
               if (pid == 0) {
                   close(read_fd);
                   child_process(write_fd, argv[i+1], ppid);
                   break;
               } else {
                   pid = fork();
               }
        
           }
        
           // don't let child run beyond this point
           if (pid == 0) {
               exit(0);
           }
        
           // parent only code
           if (pid > 0)
           {
               close(write_fd);
               while (read(read_fd, (void*)&recvd, 1) > 0) 
               {
                   wait(NULL);
                   totalwords += recvd;
               }
               close(read_fd);
           } 
           printf("Main process created %d child processes to count words in %d files\n", argc - 1, argc - 1);
           printf("Total words is %d\n", totalwords);
           printf("%d files have been counted sucessfully!\n", argc - 1);
        }