首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

使用vfork(),后用return 出现段异常有关问题

2013-03-28 
使用vfork(),后用return 出现段错误问题#includestdio.h#includeunistd.h#includesys/types.hmain()

使用vfork(),后用return 出现段错误问题
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
main()
{
   pid_t pid;
   int count=0;
   pid=vfork();
    count++;    
   printf("count=%d, pid=%d\n",count,getpid());
    return(0);
}
运行出现count=1,pid=25127
        count=1, pid=25126 后又显示“段错误”
尝试把retrurn(0); 改为 exit(0);之后运行结果  count=1;pid=25145
                                            count=2;pid=25144
查看了有关return() 和 exit()还是不理解,求解释!!!!!!
[解决办法]

NAME
       vfork - create a child process and block parent

SYNOPSIS
       #include <sys/types.h>
       #include <unistd.h>

       pid_t vfork(void);

STANDARD DESCRIPTION
       (From  XPG4  /  SUSv2  /  POSIX draft.)  The vfork() function has the same effect as fork(), except that the behaviour is undefined if the process created by
       vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or  returns  from  the  function  in  which
       vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.

ERRORS
       EAGAIN Too many processes - try again.

       ENOMEM There is insufficient swap space for the new process.

LINUX DESCRIPTION
       vfork, just like fork(2), creates a child process of the calling process.  For details and return value and errors, see fork(2).

       vfork()  is  a special case of clone(2).  It is used to create new processes without copying the page tables of the parent process.  It may be useful in per-
       formance sensitive applications where a child will be created which then immediately issues an execve().

       vfork() differs from fork in that the parent is suspended until the child makes a call to execve(2) or _exit(2).  The child shares all memory with  its  par-


       ent, including the stack, until execve() is issued by the child.  The child must not return from the current function or call exit(), but may call _exit().

       Signal handlers are inherited, but not shared.  Signals to the parent arrive after the child releases the parent.



自己读?
[解决办法]

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

int main(int argc, char ** argv )
{
  int pid = fork();

    if (pid < 0)
    {
        printf("error!");
    }
    else if( pid == 0 )
    {
        printf("This is the child process!");
    }
    else
    {
        printf("This is the parent process! child process id = %d", pid);
    }
    
    return 0;
}

[解决办法]
引用:
不理解3楼啥意思,求解释,并非让附程序??

三楼的意思是让子进程,和父进程有点区别!不过楼主的程序,return和exit应该是一样的!(本人没有验证)
[解决办法]
正如1楼所说:

vfork成功后的话严禁return, 只能调用_exit或者exec族的函数,否则后果不可预料。

热点排行