berzerk352
berzerk352

Reputation: 3

Writing a shell in C for linux, exec for one certain process is infinitely looping

This is the relevant snippet of code:

if(!strcmp(args[0],"run")){
                pid_t pid = fork();
                if(pid == 0){
                  execvp(args[1], args);
                  fprintf(stdout, "Process could not be found in this directory\n");
                  kill((int)getpid(), SIGKILL);
                }
                else{
                    if(pid < 0)
                        exit(1);

                    fprintf(stdout, "PID of Process = %d\n", pid);
                    int success = waitpid(pid, &childExitStatus, WUNTRACED | WCONTINUED);

                    if(success == -1)
                        exit(EXIT_FAILURE);
                }

            }

Now when I run a process like Libre Office math, it will only open one instance of it. However, when I try to open xterm using this code, it will continue to exec over and over, creating many instances of xterm before I do an interrupt and exit. I don't see any loops that would cause this to happen. Any insight into why this would be?

Upvotes: 0

Views: 210

Answers (2)

zwol
zwol

Reputation: 140540

In addition to jilles' answer to your immediate problem, you should know that calling fprintf if execvp fails is unwise as it can lead to duplication of previously-buffered output. It also means you cannot safely use vfork, which can still be a valuable optimization (particularly if the parent process uses a lot of memory).

There is no good way to report an exec failure, unfortunately. I tend to just do

if (pid == 0) {
    execvp(...);
    /* if we got here, something bad happened */
    _exit(127);
}

Upvotes: 0

jilles
jilles

Reputation: 11232

The execvp() call is incorrect because it passes an additional argument "run" at the start. When executing xterm in this manner, the effect is similar to xterm xterm and has xterm use xterm as the shell. The new xterm inherits a SHELL environment variable that causes it to start another xterm, until limits are exhausted.

Upvotes: 2

Related Questions