数平方的特殊过程
Special process of squaring of a number
我有一个 c 程序(赋值),它从用户输入中读取一个数字并对其执行平方运算。平方运算按以下方式完成:
- 程序调用fork()
- 在子进程中,execv() 用于调用名为“square”的可执行文件,并将数字作为命令行参数。
- 父进程等待子进程完成。
现在的问题是我们不能使用管道,写入文件来获取平方数的值。所以我认为最好的方法是 return 平方数的值,并借助 WEXITSTATUS 在父进程中获取它。
这工作正常,直到平方数小于 255(因为 WEXITSTATUS return 仅低 8 位)
所以我想问一下有没有其他可行的方法。
编辑:只允许这些:
分叉,
执行*家庭,
ato* 家族,
打印,冲刺,
分配器,
自由,
等待/等待,
开方,
退出
Yes, multiple forks are allowed. How it will help?
由于每个进程只能通过 WEXITSTAUS return 最多 1 个字节的信息,因此派生 8 个子进程来计算 8 字节浮点值的每个字节。假设 sizeof(double) == 8
每个子进程都将调用 execv 函数 - 除了子进程索引号 (0-7) 作为第二个参数外,还传递预期计算 sqrt 的平方数。
您的子进程只需要稍作修改。像这样。
int square = atoi(argv[1]);
int result_index = atoi(argv[2]);
double result = sqrt(square); // compute the square root
// now treat the double as an array of 8 bytes. Return the
// byte value of the index passed in as the second command line parameater
unsigned char* ptr = (unsigned char*)(&result);
unsigned char value = ptr[result_index]; // value is what you want to return to the parent process
exit(value); // or "return value" - whatever you are doing to set WEXITSTATUS
父进程等待所有8个子进程完成并使用每个子进程的索引重建每个
中计算的double
double result = 0; // this will contain the square root after all 8 processes have finished
unsigned char* ptr = (unsigned char*)(&result);
for (int i = 0; i < 8; i++)
{
<wait for child[i] to finish>
unsigned char value = <the WEXITSTATUS of the child process>
ptr[i] = value;
}
当所有 8 个子进程都完成并且父进程已从每个子进程中获取结果字节(将每个返回到指向双精度指针的偏移量中)时,原始值的平方根将在 result
您可以让每个分叉进程 运行 一次一个或并行。
我有一个 c 程序(赋值),它从用户输入中读取一个数字并对其执行平方运算。平方运算按以下方式完成:
- 程序调用fork()
- 在子进程中,execv() 用于调用名为“square”的可执行文件,并将数字作为命令行参数。
- 父进程等待子进程完成。
现在的问题是我们不能使用管道,写入文件来获取平方数的值。所以我认为最好的方法是 return 平方数的值,并借助 WEXITSTATUS 在父进程中获取它。 这工作正常,直到平方数小于 255(因为 WEXITSTATUS return 仅低 8 位)
所以我想问一下有没有其他可行的方法。
编辑:只允许这些:
分叉, 执行*家庭, ato* 家族, 打印,冲刺, 分配器, 自由, 等待/等待, 开方, 退出
Yes, multiple forks are allowed. How it will help?
由于每个进程只能通过 WEXITSTAUS return 最多 1 个字节的信息,因此派生 8 个子进程来计算 8 字节浮点值的每个字节。假设 sizeof(double) == 8
每个子进程都将调用 execv 函数 - 除了子进程索引号 (0-7) 作为第二个参数外,还传递预期计算 sqrt 的平方数。
您的子进程只需要稍作修改。像这样。
int square = atoi(argv[1]);
int result_index = atoi(argv[2]);
double result = sqrt(square); // compute the square root
// now treat the double as an array of 8 bytes. Return the
// byte value of the index passed in as the second command line parameater
unsigned char* ptr = (unsigned char*)(&result);
unsigned char value = ptr[result_index]; // value is what you want to return to the parent process
exit(value); // or "return value" - whatever you are doing to set WEXITSTATUS
父进程等待所有8个子进程完成并使用每个子进程的索引重建每个
中计算的double
double result = 0; // this will contain the square root after all 8 processes have finished
unsigned char* ptr = (unsigned char*)(&result);
for (int i = 0; i < 8; i++)
{
<wait for child[i] to finish>
unsigned char value = <the WEXITSTATUS of the child process>
ptr[i] = value;
}
当所有 8 个子进程都完成并且父进程已从每个子进程中获取结果字节(将每个返回到指向双精度指针的偏移量中)时,原始值的平方根将在 result
您可以让每个分叉进程 运行 一次一个或并行。