【发布时间】:2021-11-13 03:32:12
【问题描述】:
我是 C++ 和 Linux 的新手,我对如何使用 execlp() 正确地将整数参数传递给子类感到困惑。我尝试遵循此系统调用的参数要求,但是,当我执行程序时,参数未传递正确的值。字符转换让我感到困惑。
在下面的程序中,父母从终端接受性别名称对。接下来,它使用 fork() 和 exec() 系统调用将子编号、性别和姓名传递给子程序。子程序将输出语句。子编号的输出关闭(应为:1,2,3,4,...等)。但是,输出值为空白。是因为我在 execlp() 系统调用中初始化参数的方式吗?
以下是我的父程序代码 - parent.cc:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
int i, num = 0;
/* Holds the value of the number of pairs */
int pairs = (argc - 1) / 2;
pid_t pid;
cout << "I have " << pairs << " children." << endl;
/* Perform all child process depending on the number of name-gender pairs*/
for (i = 1; i <= argc-1; i+=2)
{
pid = fork();
/* Child process */
if (pid == 0)
{
char n[] = {char(num++)};
execlp("./c",n,argv[i],argv[i+1], NULL);
}
/* Parent will wait until all child processes finish */
wait(NULL);
}
cout << "All child process terminated. Parent exits." << endl;
/* Exits program */
return 0;
}
这是我的子程序-child.cc
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
/* When child process starts, it will print out this statement */
cout << "Child # " << argv[0] << ": I am a " << argv[1] << ", and my name is " << argv[2] << endl;
exit(0);
}
这是我在终端中的输出:
g++ -o parent.cc
g++ -o c child.cc
./p boy Mark girl Emily boy Daniel girl Hailey
I have 4 children.
Child # : I am a boy, and my name is Mark
Child # : I am a girl, and my name is Emily
Child # : I am a boy, and my name is Daniel
Child # : I am a girl, and my Hailey
All child process terminated. Parent exits.
【问题讨论】:
-
char n[] = {char(num++)};将创建带有不可见控制字符的字符串 -char(i)不是将数字转换为字符串的正确方法! -
我删除了c 标签,因为您的程序是 C++。它们是两种不同的语言。