cdsfiui 发表于 2017-01-11 09:45

clone()一调用,程序状态就异常了

本帖最后由 cdsfiui 于 2017-01-11 15:38 编辑

如下代码,我想看clone()是不是能创建新进程,而且让两个进程都能正常运行和打印#include<stdio.h>
#include<sched.h>
#include<unistd.h>
#include<sys/types.h>
#include<errno.h>
int f(void*arg)
{
pid_t pid=getpid();
printf("child pid=%d\n",pid);
}
char buf;
int main()
{
    printf("before clone\n");
    int pid=clone(f,buf,CLONE_VM|CLONE_VFORK,NULL);
    if(pid==-1){
      printf("%d\n",errno);
      return 1;
    }
    waitpid(pid,NULL,0);
    printf("after clone\n");
    printf("father pid=%d\n",getpid());
    return 0;
}
编译运行的结果是:
$g++ testClone.cpp && ./a.out
before clone

很奇怪,clone之后,程序就进入了异常状态
我尝试gdb,调试到clone只一句执行以后,有如下输出:
Breakpoint 1, main () at testClone.cpp:15
(gdb) n-
before clone
(gdb) n-
waiting for new child: No child processes.
(gdb) n-
Single stepping until exit from function clone@plt,-
which has no line number information.


如果我去掉waitpid这一句,那么运行结果一样,gdb的输出变成了:
(gdb) n-
before clone
(gdb) n-
Detaching after fork from child process 26709.
warning: Unexpected waitpid result 000000 when waiting for vfork-done
Cannot remove breakpoints because program is no longer writable.
It might be running in another process.
Further execution is probably impossible.
0x00007fb18a446bf1 in clone () from /lib64/libc.so.6
ptrace: No such process.

我的程序错在哪里了? 谢谢


shang2010 发表于 2017-01-11 10:51

两个进程要加锁

cdsfiui 发表于 2017-01-11 15:39

我知道了,clone第二个参数必须是指向栈底的指针,数组首地址是栈顶,反了,所以改成:

char buf;   // *** allocate more stack ***
int main()
{
    printf("before clone\n");
    int pid=clone(f,buf+sizeof(buf),CLONE_VM|CLONE_VFORK,NULL);
页: [1]
查看完整版本: clone()一调用,程序状态就异常了