I am writing a C code that acts as a Linux shell. I'm trying to create a program that can run a command such as 'sleep 7 &' in the background while simultaneously running a command like 'ps -l' in the foreground. Currently, my code is triggering my "perror("wait")" error message. Am I not forking at the correct location? Any insight is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <string.h>
int execute(char *argv[])
/*
* purpose: run a program passing it arguments
* returns: status returned via wait, or -1 on error
* errors: -1 on fork() or wait() errors
*/
{
int i = 0; /* This will be our array iterator */
size_t size = sizeof *(argv) / sizeof *(argv[0]); /* This is the size of the argv array that we will iterate through */
int pid;
int child_info = -1;
/* Check if the first argument exists */
if (argv[0] == NULL)
{ /* nothing succeeds */
return 0;
}
/* Using a for loop to traverse the argvs */
for (i; i < size; i++)
{
/* if the argv exists */
if (argv[i] != NULL)
{
/* check to see if the argv is an ampersand */
if (strcmp(argv[i], "&") == 0)
{
/* Let us know there is infact an ampersand */
printf("We have an ampersand\n");
argv[i] = '\0';
}
}
}
if ((pid = fork()) == -1)
{
perror("fork");
}
else if (pid == 0)
{
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
execvp(argv[0], argv);
perror("cannot execute command");
exit(1);
}
else
{
printf("\nProcess %d has begun in the background.\n", pid);
fork(); !!! <---- Where I'm trying to fork() and allow a new process to run in the foreground.
if (waitpid(pid, &child_info, WNOHANG) == -1)
{
perror("wait");
}
else if (waitpid(pid, &child_info, WNOHANG == 0))
{
printf("Process %d done.\n", pid);
kill(pid, SIGKILL);
}
}
return child_info;
}
Currently, it runs the sleep command but says "Wait: No Child Process".