0

我是 C 的业余爱好者,在 C 中处理字符串时遇到问题。目标是将电流添加pid到基本字符串中,然后用system(system_call). 我有以下内容:

char system_call[100] = "top -p "
char pid_string[30];

//quite a bit of other code

int main(int argc, char *argv[])
{
    pid_t pid = getpid();
    sprintf(pid_string,"%d",pid);
    strcat(system_call,pid_string);

    printf(system_call); //prints what I expect; something like 'top -p 5580'
    system(system_call); //doesn't work
}

电话只是简单地system给出。sh: system: not found我相信精通 C 的人会立即知道问题所在。我认为 C 中字符串后面的 0 可能与它有关,但我对 C 语言太糟糕了,无法识别它或不知道该怎么做。我也试过system("%s",system_call),但system只接受一个论点。我的内存分配有问题吗?任何见解都值得赞赏。

4

2 回答 2

2

看不到您的字符串构造有任何问题,也许问题是“系统”本身由于某种原因在您的系统上不起作用:-),或者“顶部”无法访问

于 2013-04-10T21:37:56.127 回答
2

在 sprintf 中使用之前,变量 pid 没有被赋值。

于 2013-04-10T21:32:34.777 回答