【问题标题】:Trying to pass variables to child process试图将变量传递给子进程
【发布时间】:2013-12-01 00:04:42
【问题描述】:

我正在尝试将变量传递给一个分叉的函数,大多数似乎都可以工作,但我需要给每个变量一个我试图传递的 argv[5] 的 id,该 argv[5] 之前没有声明。我的代码不断出现段错误,我不知道为什么。有什么想法吗?

主要

char* arg_list_consumer[] = {
        "./consume",
        argv[1], 
        argv[2],
        NULL
    };
    char* arg_list_producer[] = {
        "./produce",
        argv[1], 
        argv[2],
        argv[3],
        argv[4],
        argv[5],
        NULL
    };
   if (getppid()==1){
        producerID=0;
   }
   if(producerID==0){
        for(i=1; i<P; i++){
            sprintf(arg_list_producer[5], "%d", i);
            spawn ("./produce", arg_list_producer);
        }
        for(i=0; i<C; i++){
            sprintf(arg_list_consumer[5], "%d", i);
            spawn ("./consume", arg_list_consumer);
        }
    }

生成

int spawn (char* program, char** arg_list)
{
  pid_t child_pid;
  /* Duplicate this process.  */
  child_pid = fork();

  if (child_pid != 0)
    /* This is the parent process.  */
    return child_pid;
  else {
    /* Now execute PROGRAM, searching for it in the path.  */
    execvp (program, arg_list);
    /* The execvp function returns only if an error occurs.  */
    fprintf (stderr, "an error occurred in execvp\n");
    abort ();
  }
}

【问题讨论】:

    标签: c consumer producer


    【解决方案1】:

    arg_list_consumer 被声明为只有 4 个条目。因此,使用 [5] 对其进行索引是无效的内存操作。

    如果你想给 arg_list_consumer[5] 赋值,你必须将数组声明为至少 6 个指针大小(或者你可以再添加几个 NULL 使其大小至少为 6 个指针)。

    然后,如果你想使用 sprintf 来存储一些东西,你必须已经在目标字符串中分配了空间。由于您只有一个指针数组,这意味着您必须使用 malloc 分配一些空间:

    arg_list_consumer[5] = malloc(sizeof(char)*10);
    sprintf(arg_list_consume[5], "%d", i);
    

    (我使用了 10,但您显然应该使用您认为必要的任何长度)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多