我想用 C 创建另一个进程。 但我不知道如何将论点传递给另一个人, 使用fork()、exec() 这是我的代码
sls.c
int main() {
void start_game (const char* file_name,int N,int max_lives)
{
pid_t pid;
int child_status;
pid = fork();
if(pid!=0){
wait(&child_status);
}
else{
if(-1 == execl("./player","player",&file_name,&max_lives,(char *)NULL))
{
perror("execlp() failed");
return 1;
}
}
int r = 1+rand()%max_lives;
}
return(0);
}
我需要将 file_name 和 max_live 传递给 player.c 所以player.c可以读取同一个文件
player.c
int main(int argc,char *argv[]) {
pid_t child_pid = fork();
int child_status;
int sidekick_amount = (int)getpid%5;
void read_ints (const char* file_name)
{
// Normal read file stuff here
}
if (child_pid!=0)
{
wait(&child_status);
}
else
{
execlp("","-l",NULL);
printf("Exec error\n");
exit(-1);
}
int lives = argv[2];
printf("\nAt pos 0: Player %d has %d lives , %d sidekicks and
\n is ready to start ",(int)getppid(),lives,sidekick_amount);
read_ints(file_name);
return (0);
}
阅读文件并设置助手数量后。 player.c需要为sidekick_amount生成sidekick.c进程 作为 player.c 子元素。但我无法从 player.c 中获取 file_name 和 lives
sidekicks.c
enter code here
输出
At pos 0: Player 25477 has -5703328 lives , 1 sidekicks and is ready to start
感谢您的所有帮助,非常感谢所有答案
最佳答案
您需要将整数 max_lives
转换为字符串,以便可以将其作为函数参数传递。当您传递文件名时,只需传递字符串本身,而不是指针的地址。
void start_game (const char* file_name,int N,int max_lives)
{
pid_t pid;
int child_status;
pid = fork();
if(pid!=0){
wait(&child_status);
}
else{
char max_lives_str[20];
sprintf(max_lives_str, "%d", max_lives);
if(-1 == execl("./player","player", file_name, max_lives_str, (char *)NULL))
{
perror("execlp() failed");
return 1;
}
}
int r = 1+rand()%max_lives;
}
关于C Linux 你如何将参数传递给另一个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36463571/