PDA

View Full Version : Question about fork and exec



steli89
04-12-2010, 12:23 AM
I'm a newbie to processes in general and i have this code:


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


int main() {
char buffer[100];
int pid, status;
while(1) {
printf("> ");
fgets(buffer, sizeof(buffer), stdin);
printf("here\n");
switch(pid = fork()) {
case 0 :
system(buffer);
}
waitpid(pid, &status, 0);
}
}

( there are too many includes, i know :) ).

I have to simulate a shell for a university homework and i have the following problem:
Wherever i run this, i read a command from the keyboard and the "here" print always comes AFTER the command's output. Why is this happening? It's very important for my homework.

Stelian

Shakti
04-12-2010, 03:17 AM
Try to flush the output buffer using fflush after printf("here")

MK27
04-12-2010, 05:10 AM
Very likely the command's output is to stderr, and not stdout. Stderr is not buffered, and is a separate stream, so it is possible for stderr output to appear while stdout still has unflushed content.

Use fflush like Shaki says or:


fprintf(stderr, "here\n");

steli89
04-12-2010, 02:47 PM
Thank you! fflush seems to be the solution

CornedBee
04-13-2010, 07:17 AM
On a side note, system() returns normally, so you're leaving a lot of zombies behind. You need to terminate the child process after calling system(), or better yet, use some exec() variant instead.