1

I am trying to send my command line arguments through from the child process to the parent process using a pipe but can't figure out what I'm doing wrong. My code is below. Any help is appreciated. Thanks in advance.

int main(int argc, char argv[])
   pid_t child;
   int fd[2];

   pipe(fd);
   if((child = fork() == 0)
   {
      int len = strlen(argv[1]);
      close(fd[0];
      write(fd[1], argv[1], len);
      exit(0);
   }
   else //Assuming process won't fail for now
   {
      char src[10]; //Just using 10 for now, no arguments have more than 10 characters
      read(fd[0], src, (strlen(src)));
      fprintf(stderr, "%s\n", src);
      close(fd[0]);
   }
}
4

3 回答 3

2

你有一堆小错误,但据我所知,不管你信不信,这可能是你真正的问题。

read(fd[0], src, (strlen(src)));

我的猜测是第一个 char 为 null 并且您成功读取了 0 个字节。

改成

  read(fd[0], src, (sizeof(src)));

在您较大的项目中,请确保您在循环中读取和写入。不保证您可以读取或写入您指定的内容。

于 2013-10-01T20:24:22.890 回答
1

您可能需要先关闭else块内的 fd[1]。

检查这个例子

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
    int
    main(int argc, char *argv[])
    {
            int pipefd[2];
            pid_t cpid;
            char buf;
            if (argc != 2) {
            fprintf(stderr, "Usage: %s <string>\n", argv[0]);
            exit(EXIT_FAILURE);
            }
            if (pipe(pipefd) == -1) {
                    perror("pipe");
                    exit(EXIT_FAILURE);
            }
            cpid = fork();
            if (cpid == -1) {
                    perror("fork");
                    exit(EXIT_FAILURE);
            }
            if (cpid == 0) {    /* Child reads from pipe */
                    close(pipefd[1]);          /* Close unused write end */
                    while (read(pipefd[0], &buf, 1) > 0)
                            write(STDOUT_FILENO, &buf, 1);
                    write(STDOUT_FILENO, "\n", 1);
                    close(pipefd[0]);
                    _exit(EXIT_SUCCESS);
            } else {            /* Parent writes argv[1] to pipe */
                    close(pipefd[0]);          /* Close unused read end */
                    write(pipefd[1], argv[1], strlen(argv[1]));
                    close(pipefd[1]);          /* Reader will see EOF */
                    wait(NULL);                /* Wait for child */
                    exit(EXIT_SUCCESS);
            }
    }
于 2013-10-01T19:41:02.390 回答
0

你已经假设这fork()不会失败。

但是呢pipe()??

假设两者都成功完成,则需要正确关闭 fds。

你的 if-else 块应该是这样的。

if((child = fork() == 0)
   {
      int len = strlen(argv[1]);
      close(fd[0]);//I assume this was your typo. otherwise it would not even get compiled
      write(fd[1], argv[1], len);
      close(fd[1]);
      exit(0);
   }
else //Assuming process won't fail for now
   {
      close(fd[1]);
      char src[10]; //Just using 10 for now, no arguments have more than 10 characters
      read(fd[0], src, (strlen(src)));
      fprintf(stderr, "%s\n", src);
      close(fd[0]);
   }
于 2013-10-01T19:52:20.797 回答