linux函数种的exit,main函数中exit(0)和return(0)的区别。(linux下c编程)

#include"stdio.h"

#include"errno.h"

#include"unistd.h"

#include"stdlib.h"

int main(void)

{

pid_t pid;

int count=0;

if((pid=vfork())==-1)

{

printf("vfork error:%sn",strerror(errno));

exit(1);

}

count++;

printf("count=%dn",count);

return(0);

}

执行结果为:

count=1

count=1

段错误

而把return(0)换成exit(0)后

就能顺利执行呢?此时结果为

count=1

count=2

期待各位大侠回答

|

Parent and child processes share the same stack space within the

[vfork,exec] window.  If the size of the stack has been changed

within this window by the child process (return from or call to a

function, for example), it is likely that the parent and child

processes will be killed with signal SIGSEGV or SIGBUS.

|

vfork() differs from fork(2) in that the parent is suspended until the child

terminates (either normally, by calling _exit(2), or abnormally, after

delivery of a fatal signal), or it makes a call to execve(2).  Until that

point, the child shares all memory with its parent, including the stack.  The

child must not return from the current function or call exit(3), but may call

_exit(2).

|

正如4楼所说,问题在于vfork.

如果没有使用vfork(), 在main函数中return (0)和exit(0)是没有区别的。

|

#include"stdio.h"

#include"errno.h"

#include"unistd.h"

#include"stdlib.h"

int main(void)

{

pid_t pid;

int count=0;

if((pid=vfork())==-1)

{

perror("vfork()");

exit(1);

}

count++;

printf("%dn",getpid());

printf("count=%dn",count);

exit (0);

}

return 0时,一部分结果

22985

count=1

15974

count=2

22986

count=1

15974

count=2

22987

count=1

15974

count=2

22988

count=1

15974

count=2

22989

count=1

15974

count=2

22990

count=1

15974

count=2

22991

count=1

15974

count=2

22992

count=1

15974

exit 0时的结果:

23037

count=1

23036

count=2

return 0只是告诉linux  main函数的返回值是0

由于创建进程时,没结束进程的运行,父子进程会一直运行下去

exit 0表示正常退出函数

|

return(0) 在main函数中返回是等同于exit(0)的,exit(0) 无非就是做下清理工作

ls说上父进程会一直跑下去?测试过没?

|

return 函数返回。。结束一个函数

exit是抛出异常。。。结束整个进程

|

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值