Andy Vavilov
Andy Vavilov

Reputation: 199

Child process never executes after fork

I have to make a C program that gives to the parent a string, the parent edits it, puts into a pipe, then the child validates it and sends it back. For some reason only the parent executes. I wanted the parent to send the text, then wait for the execution of the child, and read the answer. But the code simply ignores the child completely.

Here's the snippet:

char response[10];
pid_t pid = fork();
int p[2];
pipe(p);
if(pid!=0)
{
    char username[255];
     CutString(8,command,username); // a function of mine i verified 
     write(p[1],username,sizeof(username));
     close(p[1]);
     wait(NULL);
     read(p[0],response,8);//the answer is always 8 bytes
     close(p[0]);
}
else //never gets here
{
     char buffer[255];
     size_t bufferIndex=0;
     char ch;
     while (ch != '\0')
     {
         read(p[0],&ch,1);
         buffer[bufferIndex++]=ch;
     }
     close(p[0]);
     f=fopen("config.txt","r");
     write(p[1],SearchInFile(f,buffer),8);
     close(p[1]);
}

Upvotes: 1

Views: 304

Answers (1)

dash-o
dash-o

Reputation: 14491

The 'child' part of the above code has few errors, causing it to execute quickly, without side effect, and then to exit.

  1. The 'while (ch != 0)' relies on uninitialized 'ch' var. On my build (cc -g), ch is initialized to zero, resulting in zero execution of the while loop.
  2. There is no test to check if fopen (config.txt) actually works. If it does not exists, code may crash.
  3. At the point of writing to p[1] (write(p[1]), the input part (p[0]), already closed. Most likely resulting in SIGPIPE.

Side comment: it's unclear what the program is trying to do.

EDIT 2019-10-25:

Possible additional issue:

  1. If the uninitialized ch (in the child part) start with non-zero value, the code may fall into wait-forever mode on the 'read' statement, since nothing was written into the pipe.

Upvotes: 3

Related Questions