简体   繁体   中英

Ending child process without returning a value

I am basically creating a function which calls upon a unix built in function and redirect its output to "myexec.txt" . So i called on open and dup2 in the child process. They redirect the output of execve to "myexec.txt" . Upon calling execve , the child process is terminated and every other standard output after the execution of execve will now be directed to the terminal. I am seeking a way to terminate the child process in case of an unsuccesul call to execve , in order to stop the output redirection to myexec.txt . I know using exit works but is there a way to kill this process without returning a value? My function needs to return void .

Here is my code chunk. I purposely give execve a non existent path.

void myexec()
{
    pid_t pid;
    pid = fork();
    if(pid == 0)
    {
        printf("executing ls\n");
        char *argv[] = {"ls", 0};
        int fd = open("myexec.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
        dup2(fd, 1);
        dup2(fd, 2);
        close(fd);
        execve("/bsin/ls", &argv[0], NULL);
        fprintf(stderr, "Failed to execute");
        ......
    }
    wait(NULL);
    printf("Function execution have been attempted");
}

Do not call exit . That's a serious mistake that has caused severe bugs in the past with significant security implications.

Call _exit . You can pass it a zero, it doesn't matter if the parent doesn't care whether the child succeeded or failed. Since _exit is guaranteed not to return, you don't need to put anything else after that.

if(pid == 0)
{
    printf("executing ls\n");
    char *argv[] = {"ls", 0};
    int fd = open("myexec.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
    dup2(fd, 1);
    dup2(fd, 2);
    close(fd);
    execve("/bsin/ls", &argv[0], NULL);
    fprintf(stderr, "Failed to execute");
    _exit(EXIT_FAILURE);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM