C Linux 你如何将参数传递给另一个程序?

标签 c linux ubuntu fork exec

我想用 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_namema​​x_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_namelives

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/

相关文章:

c - Ubuntu 第一次编译内核模块

linux - 无法使用文件/etc/docker/daemon.json : EOF 配置 Docker 守护程序

linux - 在所有子目录中运行 qsub 命令

ubuntu - oembed - 500 内部服务器错误

c++ - 将文件拆分为相等的字节部分,由完整的字分隔 (C/C++)

c - 最后一次 strcpy() 调用后 char* s2 到底如何以及为何发生变化?

CreateThread 中的转换错误

Linux:为了使用 emacs,将 Windows 键映射到 M-x

c - 如何创建一个 TCP 服务器-客户端程序,将 200 个 tcp 流从源发送到目的地?

java - Nutch - 无法从资源 org/sonar/ant/antlib.xml 加载定义