I wrote a few code to test fork like following:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>

int DemoFork()
  {
    pid_t pid,par_pid;
    par_pid = getpid();
    pid = fork();
    switch (pid) {

      case -1: printf("failure!\n"); break;

      case  0: printf("I am child!, parent is %d(\n",par_pid); break;

      default: printf("my child is %d\n",pid); break;

    }
    for(; ; ) { /* do something here */ }

  }

and I wrote a routine to test structure size.

typedef char arr_name[8];

typedef struct
{
        arr_name a;
        int len;
}demostr;

int teststr(arr_name str)
{
  demostr ab;
  strncpy(ab.a,str,sizeof(str));
  [B][I]printf("size of data type = %d,size of data = %d, size of input para = %d, a = %s",sizeof(arr_name), sizeof(ab.a), sizeof(str),ab.a);[/I][/B]
}

then I wrote a main.

int main()
{
   teststr();
   DemoFork();
}

after running, I use "ps -ef" to check, I found only parent Process is there and I cannot find the child process. If I removed teststr() call in the main(). the two process is there. Who meet such problem when using fork()?

thanks a lot.


New finding: I found the problem is printf() line in teststr, If I remove this line, there is no problem at all. But I don't know the reason, who can help to explain it?

thanks a lot.

Problem of your programm is not a fork()
Try to place endless for in the teststr function, and after that place calling DemoFork() function before calling teststr()

Why you call teststr function without any arguments?

Hello, sorry, I made a mistake when calling teststr. I have changed it already.

teststr(); -----> teststr("abc");

Problem of your programm is not a fork()
Try to place endless for in the teststr function, and after that place calling DemoFork() function before calling teststr()

Why you call teststr function without any arguments?

---------------------------------------------------------
sorry, I made a mistake when calling teststr. I have changed it already.

teststr(); -----> teststr("abc");

Would you please explain why the child process is gone in my code?
I do not quite understand your solution, would you please show me how to write the code? thanks a lot.

This article has been dead for over six months. Start a new discussion instead.