我正在尝试使用 clone() 创建一个子进程来 exec() 某些程序。我知道 exec() 替换了原来的进程,调用它的进程应该以它结束,所以我使用一个子进程来调用 exec()。但是,由于某些原因,在 exec() 之后,我的父进程也崩溃了。有人能告诉我为什么会这样吗? (如果我用 fork 或 vfork 替换克隆,它就可以工作)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sched.h>
void delNL(char * arry){ //A function to delete the newline at the end of the array
char * position;
position = strchr(arry,'\n');
*position = '\0';
}
int mySysC(char * command){ //clone funtion
char *cmd[10]={" "};
int nb=0;
int cnb=0;
while(command[nb]!='\0'){
char coa[10];
int cici=0;
while(command[nb]!=' ' && command[nb]!='\0'){
coa[cici]=command[nb];
nb++;
cici++;
}
coa[cici]='\0';
char *nad=(char *)malloc(10);
strcpy(nad,coa);
cmd[cnb]=nad;
cnb++;
if(command[nb]==' '){
nb++;
}
}
cmd[cnb]=NULL;
execvp(cmd[0],cmd);
exit(0);
}
void my_system_c(char * command){ //clone version
void * stack = (void *)malloc(10000);
void * stackTop = stack + 100000;
pid_t pid = clone((void *)mySysC(command),stackTop,CLONE_THREAD,NULL); //clone
waitpid(pid,NULL,0);
}
int main(){
char commdd[100];
char ex[10]="os_exit";
while(1){
printf("Please enter your command or enter \"os_exit\" to exit:\n");
fgets(commdd,100,stdin);
delNL(commdd);
if(strlen(commdd)>0 && strcmp(commdd,ex)!=0){
my_system_c(commdd); //select version
}
else if(strcmp(commdd,ex)==0) break;
else printf("Empty command\n");
}
return 0;
}
execvp(cmd[0],cmd);这就是使整个程序崩溃的原因。我在之前和之后添加了两张打印品,后面的一张永远不会运行。我不明白,因为我认为 clone 就像 fork 一样工作,它创建一个新进程,而 chile 进程的结束不会影响父进程?
谢谢!!!
最佳答案
clone(…CLONE_THREAD…)
不是您要查找的 clone()
。它在与父进程相同的线程组中创建一个新进程,并且:
If any of the threads in a thread group performs an
execve(2)
, then all threads other than the thread group leader are terminated, and the new program is executed in the thread group leader.
如果您正在寻找一种不使用 fork()
来启动进程的方法,请考虑使用 posix_spawn()
相反。
此外,您传递给 clone()
的堆栈指针无效。您分配的堆栈有 10,000 字节大,但堆栈指针超出堆栈起点 100,000 字节,超出堆栈终点 90,000 字节。
关于c - 为什么我的父进程在 exec() 之后也会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52570994/