简体   繁体   中英

C - How do I run a program in the background using exec?

There is a program I can run on terminal like so: ./program &

But I'm trying to do it using execvp and it isn't working:

            pid = fork();
            char *argv[3] = {"./program", "&",  NULL};

            if ( pid == 0 ) {
                execvp( argv[0], argv );
            }
            else{
                wait(NULL);
            }

What did I do wrong here?

The "&" you have in the argv array isn't going to do what you want, and may be the source of your problem here. That's a place for program arguments, and & is a shell command, not a program argument. Remove it since the ./program will run in a separate process anyway since you've forked.

As answered by Greg Hewgill , the ending & is a shell syntax (it is technically not a shell command) related to job control .

In your question, it is unclear why you need it. You could just not use that "&" , and your code should work. Read also about background processes , about terminal emulators , about process groups . Read the tty demystified .

BTW, you could instead of wait use waitpid(2) and specify the pid. You generally need some waiting (eg wait , waitpid , wait4(2) , etc ....) to avoid having zombie processes . You may want to handle the SIGCHLD signal, but read signal(7) & signal-safety(7) .

Perhaps you want to use the daemon(3) function. See also setsid(2) , setpgrp(2) , and credentials(7) . Otherwise, you probably should call wait much later in your program. You might want to redirect (using dup2(2) ), perhaps to /dev/null , to some other open(2) -ed file descriptor, to some pipe(7) , etc..., the stdin (and/or stdout and stderr ) of your child process. You may also want to multiplex input or output using poll(2) .

Your code should handle the failure of fork(2) (when it gives -1), perhaps using perror(3) in such case. You also should handle failure of execvp(3) .

In some limited and specific particular cases, you could want to popen(3) a sh , nohup(1) , batch , at , or bash but you generally don't need that.

(without understanding your motivations, and why you want to run something in the background , we can't help you more)

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