分叉时产生的错误

Error caused when forking

本文关键字:错误 分叉      更新时间:2023-10-16

我有以下代码,它派生了两个新进程,从一个进程中取出标准文件的内容并将其保存到一个文件中。它可以正常运行并保存文件,但是在调用函数(无论它是什么)返回以下行之后,会抛出EXC_BAD_ACCESS错误。为什么?

void test(vector<string> inp,int i){
    int fds[2]; // file descriptors
    long count;  // used for reading from stdout
    int fd;     // single file descriptor
    char c;     // used for writing and reading a character at a time
    pid_t pid;  // will hold process ID; used with fork()
    pipe(fds);
    // child process #1.
    fd = open((inp[i+1]).c_str(), O_RDWR | O_CREAT, 0666);
    if (fork() == 0) {
        if (fd < 0) {
            return;
        }
        dup2(fds[0], 0);
        // Don't need stdout end of pipe.
        close(fds[1]);
        // Read from stdout...
        while ((count = read(0, &c, 1)) > 0)
            write(fd, &c, 1); // Write to file.
        exit(0);
        // child process #2
    } else if ((pid = fork()) == 0) {
        dup2(fds[1], 1);
        // Don't need stdin end of pipe.
        close(fds[0]);
        // Output contents of the given file to stdout.
        char **arguments = getArguments(inp[i]);
        execvp(arguments[0], arguments);
        perror("execvp failed");
        exit(0);
        // parent process
    } else {
        waitpid(pid, NULL, 0);
        close(fds[0]);
        close(fds[1]);
    }
}

这个很适合我:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
void test(/*vector<string> inp,int i*/){
    int fds[2]; // file descriptors
    long count;  // used for reading from stdout
    int fd;     // single file descriptor
    char c;     // used for writing and reading a character at a time
    pid_t pid;  // will hold process ID; used with fork()
    pipe(fds);
    // child process #1.
    fd = open(/*(inp[i+1]).c_str()*/"/tmp/output", O_RDWR | O_CREAT, 0666);
    if (fork() == 0) {
        if (fd < 0) {
            return;
        }
        dup2(fds[0], 0);
        // Don't need stdout end of pipe.
        close(fds[1]);
        // Read from stdout...
        while ((count = read(0, &c, 1)) > 0)
            write(fd, &c, 1); // Write to file.
        _exit(0);
        // child process #2
    } else if ((pid = fork()) == 0) {
        dup2(fds[1], 1);
        // Don't need stdin end of pipe.
        close(fds[0]);
        // Output contents of the given file to stdout.
        char **arguments = new char*[2];/*getArguments(inp[i]);*/
        arguments[0]=(char*)"/bin/bash";
        arguments[1]=0;
        execvp(arguments[0], arguments);
        perror("execvp failed");
        _exit(0);
        // parent process
    } else {
        waitpid(pid, NULL, 0);
        close(fds[0]);
        close(fds[1]);
    }
}
int main(int argc, char* argv[]){
    test();
}

试着告诉你的错误出现在哪里或显示更多的程序,所以我可以尝试复制你的条件