Thread: Question about fork and exec

  1. #1
    Registered User
    Join Date
    Apr 2010

    Question about fork and exec

    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);
    		switch(pid = fork()) {
    			case 0 :
    		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.


  2. #2
    Registered User
    Join Date
    Aug 2003
    Try to flush the output buffer using fflush after printf("here")

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    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");
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Apr 2010
    Thank you! fflush seems to be the solution

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    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.
    All the buzzt!

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 10-14-2009, 04:44 PM
  2. Replies: 3
    Last Post: 06-02-2009, 06:13 PM
  3. fork + exec
    By vipul_vgp in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 08:00 AM
  4. Signals, fork(), wait() and exec()
    By DJTurboToJo in forum C Programming
    Replies: 7
    Last Post: 03-18-2008, 09:14 AM
  5. Procesees, fork(), wait() and exec()
    By Stewdent in forum Linux Programming
    Replies: 1
    Last Post: 02-20-2003, 11:34 AM