Chinaunix

标题: fork()的奇怪问题。请赐教 [打印本页]

作者: baiyoung    时间: 2006-08-29 16:58
标题: fork()的奇怪问题。请赐教
小弟不才,新学linux C 程序设计,抄了一份C程序,输出的结果怎么和预期的不一样?请指教
预期:
输出5次:This is child
输出3次:this is the parent
结果:
一直无穷尽输出下去
=====================================
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main (int argc, char * argv[])
{
  pid_t pid;
  char *message = 0;
  message = (char *)malloc(sizeof(char) * 100);
  int n;

  printf("fork Programming start\n");
  pid = fork();
  switch(pid)
  {
  case -1:
    perror("fork failed");
    exit(0);
  case 0:
    message="This is child";
    n = 5;
    break;
  default :
    message = "this is the parent";
    n = 3;
    break;
  }

  for(; n > 0; n++)
  {
    puts(message);
    sleep(1);
  }
  free(message);
  message = 0;
  exit(0);
}
作者: baiyoung    时间: 2006-08-29 17:04
自己把问题解决了,习惯性的错误
for(; n > 0; n--)
  {
    puts(message);
    sleep(1);
  }
作者: sithui    时间: 2006-08-29 17:11
你得到正确的结果了吗?
作者: baiyoung    时间: 2006-08-29 17:31

当然是顺序与我上面说得不一样了
fork Programming start
This is child
this is the parent
This is child
this is the parent
this is the parent
This is child
/home/ibas6/wanglu$This is child
This is child
作者: coldwarm    时间: 2006-08-29 17:58

  1. message = (char *)malloc(sizeof(char) * 100);
复制代码

动态分配100字节的内存,
如果你包含了stdlib.h头文件的话,不用进行强制类型转化的,c++才需要.


  1. message="This is child";
复制代码

将指针指向一个字符串常量,
现在message和以前动态分配的内存没关系了,

  1. free(message);
复制代码

应该出现segment fault才正常.

free只能用于释放由malloc的到的内存.

你用的什么编译器.
作者: wz_uestc    时间: 2006-08-29 19:37
标题: 回复 5楼 coldwarm 的帖子
楼上的分析得很有道理哈!
并且最好是   char  *message=NULL;




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2