Background process (Daemon) in C not execvp () -ing

So, I am trying to start a background process and execvp from it. When I enter cp / path / file / var / tmp, the process does not copy the file.

Here is my code for reference:

void cmd_bg(char command[])
{
        pid_t process_id = 0;
        pid_t sid = 0;
        char* argv[512];
        getArgv(command,argv);
        // Create child process
        process_id = fork();
        // Indication of fork() failure
        if (process_id < 0)
        {
                printf("fork failed!\n");
                // Return failure in exit status
                exit(1);
        }
        // PARENT PROCESS. Need to kill it.
        if (process_id > 0)
        {
                printf("process_id of child process %d \n", process_id);
                // return success in exit status
                exit(0);
        }
        //unmask the file mode
        umask(0);
        //set new session
        sid = setsid();
        if(sid < 0)
        {
                // Return failure
                exit(1);
        }
        // Change the current working directory to root.
        chdir("/");
        // Close stdin. stdout and stderr
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);


        execvp(argv[0],argv);

        }
}
void getArgv(char command[], char* argv[512])
{
        char *token;
        int count = 0;
        int pid = 0;
        int ex = 0;
        char *absPath;
        char pwdtemp[512];
        strcpy(pwdtemp,pwd);

        token = strtok(command, " ");
        while(token!=NULL)
        {
                argv[count++] = token;
                printf("%s\n",argv[count-1]);
                token = strtok(NULL," ");
        }
        argv[count] = '\0';
}

I sincerely hope someone can help me. Thank!

EDIT : I found a solution. I CAN’T RECEIVE ITSELF THAT I DO NOT NEED TO RECEIVE 100 RETURNS. TAKE FOR PEOPLE WHO CAN LOOK THIS FUTURE IN THE FUTURE:

OK I understood the problem.

First, I commented

close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
chdir("/");

Next, instead of directly calling cmd_bg, I created:

void temp1(char command[])
{
    int pid = fork();
    if(pid==0)
        cmd_bg(command);

    else
        waitpid(-1, NULL, 0);
}

Now it works! Thanks a ton for your guys!

+3
source share
3 answers

Have you tried without closing standard input, standard output, standard error

0

, execvp ( ) , . .

0

any chance you called your program cp? if so, you execvp()will call the program again and again, instead /bin/cp. It would also be useful to get the full code.

0
source

All Articles