Justin Warner
Justin Warner

Reputation: 879

pid from fork() never goes to parent, only child

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "structs.h"
#include "server.h"
#include "client.h"


int main(void)
{

  pid_t pid;
  int mypipe[2];
  int otherPipe[2];

  if(pipe(mypipe))
    {
      printf("Error in making a pipe");
    }
  if(pipe(otherPipe))
    {
      printf("Error creating another pipe");
    }
  if((pid=fork()) == -1)
    {
      perror("fork");
      exit(1);
    }
  printf("Child ID: %d" , pid);
  if(pid == 0)
    {
      close(mypipe[1]);
      close(otherPipe[0]);
      client *c = new client(mypipe[0], otherPipe[1]);
      wait(NULL);
      //c->startProgram();
      //return EXIT_SUCCESS;
    }
  else
    {
      printf("Yo");
    close(mypipe[0]);
    close(otherPipe[1]);
    server s;
    s.fdIn = otherPipe[0];
    s.fdOut = mypipe[1];
    s.startServer();
    //wait(NULL);
    //return EXIT_SUCCESS;
    }
}

Above is my code. The child process runs fine (If I remove that comment obviously), however the else never gets executed (Or am I missing something in the terminal?).

Here's a screen shot of the output: https://i.sstatic.net/MawUJ.png

Any ideas on why it's not going to the else/parent spot?

Thanks!

Upvotes: 1

Views: 326

Answers (1)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143279

Could it be because stdio is buffered? Try flushing output after printfing the child id. Or adding a \n. Or fprintfing it to stderr.

EDIT: Just to clarify. My guess is not that it's the reason it's not getting to parent, for it is, it is why you do not see the output you expect.

Upvotes: 3

Related Questions