I'm having a problem with fork running in a function I'm using to create a terminal for a school project.
This function is called to handle the user input when they type in a command:
void handleExternalCommands(char ** arr)
{
pid_t pid;
pid = fork();
printf("pid is ", (long) pid);
if (pid == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
int status = execvp(arr[0], arr);
printf("im in the child process");
if (status == -1)
{
// error handle
}
}
wait();
}
However, no matter what I type in, I can't actually make it inside of the if statement. If I try to find out what's going on with pid by using:
printf(pid);
I get a segmentation fault error?
Thanks for your help in advance, everyone.
UPDATE:
I've changed the code to what it is above. Printing the pid only happens once and it prints nothing: "pid is "
If the execvp()
works, the printf()
is never executed. You'd only see the message from printf()
if (a) you added a newline to the end and (b) the execvp()
failed. (OK: you might see it eventually even without a newline, but the newline is a good idea.)
Move the printf()
to before the execvp()
and (definitely) add the newline and you should see the information. See also printf()
anomaly after fork()
, but note you are running into a different consequence of not terminating printf()
output with newlines.
As to printf(pid)
crashing, you need to read the manual on printf()
and add compiler options so you get told about erroneous use.
You probably need:
printf("PID %d\n", pid);
That assumes that pid_t
is sufficiently compatible with int
not to run into trouble — a moderately safe assumption, but one which can be avoided by writing:
printf("PID %d\n", (int)pid);
(or use int pid;
as the definition). But the key point is that you need to use printf()
correctly, and execvp()
does not return unless it fails.