[英]C program asking for user input multiple times
编写一个演示共享内存的非常基本的C程序。 程序需要继续计算两个输入的总和,直到用户执行^C
(此处未显示)为止。
到目前为止,我的工作是让父母获取用户输入,然后告诉孩子计算总和,然后由父母打印总和(如作业所示)。
附件是我的代码。
// Fork the process
while(1) {
// Declare a shared memory integer array
int *shared_ints = mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
int x;
int y;
shared_ints[3] = 0;
if((pid = fork()) < 0) {
printf("Fork error \n");
exit(-1);
} else if(pid > 0 && shared_ints[3] == 0) { // Parent code
// Ask user for first input
printf("Enter your first number:");
scanf("%d", &x);
printf("\n");
// Ask user for second input
printf("Enter your second number:");
scanf("%d", &y);
printf("\n");
// Assign first value to shared memory
shared_ints[0] = x;
// Assign second value to shared memory
shared_ints[1] = y;
// Tell child that it can compute the sum now
shared_ints[3] = 1;
// Trap parent in a while-loop while the child
// computes the sum
while(shared_ints[3] == 1);
// Child has completed calculating the sum and
// the parent can print the sum
if(shared_ints[3] == 2) {
printf("The sum is: %d", shared_ints[2]);
printf("\n");
}
} else { // Child code
// Wait for parent to accept input values
while(shared_ints[3] == 0);
// Calculate the sum
shared_ints[2] = shared_ints[0] + shared_ints[1];
// Tell parent sum has been calculated
shared_ints[3] = 2;
}
}
求和计算一直有效,直到我转到求和计算的第四次迭代(这是输出)为止:
Created shared memory object /my_shared_memory
Shared memory segment allocated correctly (16 bytes).
Enter your first number:1
Enter your second number:2
The sum is: 3
Enter your first number:Enter your first number:3
Enter your second number:4
The sum is: 7
Enter your first number:Enter your first number:5
Enter your second number:6
The sum is: 11
Enter your first number:Enter your first number:7
Enter your second number:8
Enter your second number:9
Enter your second number:
我看到的一个有趣的错误是,在我打印了总和之后,程序会按以下建议两次请求第一个输入: Enter your first number:Enter your first number:3
,然后在第四次求和迭代中,要求第二个输入在计算总和之前先数次。
问题在于您要在外部while
循环的每个迭代上进行分叉,因此第一次出现时,您有一个孩子,然后您有一个认为自己已经长大并且是父母的孩子(以及知道它是父母)。 随着您的继续,情况变得越来越糟。
另一个问题是您在外部while
循环的每次迭代中分配共享内存。 我不确定这是否确实是内存泄漏,但这可能不是一个好主意。
修理:
mmap()
和fork()
移到while (1)
循环之外。 main()
,全部具有一个循环,该循环从用户读取,传输到子进程,从子进程读取结果并继续。 它使用标头"stderr.h"
并使用我编写的代码中的err_setarg0()
和err_syserr()
函数,因为错误报告至关重要,并且这些操作很容易。 您应该能够从我那里获得带有该标头和那些功能的工作版本的SO代码。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "stderr.h"
static void be_childish(int *shared_ints);
static void be_parental(int *shared_ints);
int main(int argc, char **argv)
{
const char *file = "fidget";
int shared_seg_size = 4 * sizeof(int);
err_setarg0(argv[0]);
if (argc > 1)
file = argv[1];
int fd = open(file, O_RDWR|O_CREAT, 0600);
if (fd < 0)
err_syserr("Failed to open file %s for read/write\n", file);
/* Assume sizeof(int) == 4 */
if (write(fd, "abcdefghijklmnop", shared_seg_size) != shared_seg_size)
err_syserr("Failed to write %d bytes to %s\n", shared_seg_size, file);
int *shared_ints = mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shared_ints == 0)
err_syserr("Failed to mmap file %s\n", file);
shared_ints[3] = 0;
int pid;
if ((pid = fork()) == -1)
err_syserr("Failed to fork\n");
else if (pid == 0)
be_childish(shared_ints);
else
be_parental(shared_ints);
return 0;
}
static void be_childish(int *shared_ints)
{
while (1)
{
// Wait for parent to generate input values
while (shared_ints[3] == 0 || shared_ints[3] == 2)
{
printf("Child: %d\n", shared_ints[3]);
usleep(500000);
}
if (shared_ints[3] != 1)
{
printf("Child: exiting\n");
return;
}
// Calculate the sum
shared_ints[2] = shared_ints[0] + shared_ints[1];
printf("Child: calculated %d + %d = %d\n", shared_ints[0], shared_ints[1], shared_ints[2]);
// Tell parent sum has been calculated
shared_ints[3] = 2;
}
}
static void be_parental(int *shared_ints)
{
while (1)
{
int x;
int y;
// Ask user for first input
printf("Enter your first number:");
if (scanf("%d", &x) != 1)
{
printf("Parent: exiting\n");
shared_ints[3] = -1; /* Tell child to exit */
return;
}
printf("\n");
// Ask user for second input
printf("Enter your second number:");
if (scanf("%d", &y) != 1)
{
printf("Parent: exiting\n");
shared_ints[3] = -1; /* Tell child to exit */
return;
}
printf("\n");
// Assign first value to shared memory
shared_ints[0] = x;
// Assign second value to shared memory
shared_ints[1] = y;
// Tell child that it can compute the sum now
shared_ints[3] = 1;
// Trap parent in a while-loop while the child
// computes the sum
while (shared_ints[3] == 1)
{
printf("Parent: %d\n", shared_ints[3]);
usleep(500000);
}
// Child has completed calculating the sum and
// the parent can print the sum
if (shared_ints[3] == 2)
{
printf("The sum is: %d", shared_ints[2]);
printf("\n");
}
else
{
printf("Parent: unexpected control %d - exiting\n", shared_ints[2]);
shared_ints[3] = -1; /* Tell child to exit */
return;
}
}
}
该代码在忙等待循环中进行调试,每个读取周期有0.5秒的延迟。 您可以调整它以适合自己,并在确定对您有用时也失去输出。 请注意,除非您指定要创建/销毁的备用名称,否则代码会破坏文件fidget
。 退出时不会删除文件; 它可能应该。
$ ./dualproc
Enter your first number:Child: 0
1
Enter your second number:Child: 0
2
Parent: 1
Child: calculated 1 + 2 = 3
Child: 2
The sum is: 3
Enter your first number:Child: 2
Child: 2
3
Enter your second number:Child: 2
4
Parent: 1
Child: calculated 3 + 4 = 7
Child: 2
The sum is: 7
Enter your first number:Child: 2
q
Parent: exiting
$ Child: exiting
$
父母先于孩子退出; 那里没有什么大的惊喜。 如果愿意,可以升级代码以使用wait()
等待子项退出。
注意:这里有一个问题,在极端情况下,父母退出,孩子仍在等待父母输入值-如果用户在shared_ints [3]!= 0时中断程序会发生这种情况
为了展示@Jonathan Leffler的出色答案,这是我的修复建议:
/* These are better declared outside the while loop */
// Declare a shared memory integer array
int *shared_ints = mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
int x;
int y;
// Fork the process
while(1) {
shared_ints[3] = 0;
if((pid = fork()) < 0) {
printf("Fork error \n");
exit(-1);
} else if(pid > 0 && shared_ints[3] == 0) { // Parent code
// Ask user for first input
printf("Enter your first number:");
scanf("%d", &x);
printf("\n");
// Ask user for second input
printf("Enter your second number:");
scanf("%d", &y);
printf("\n");
// Assign first value to shared memory
shared_ints[0] = x;
// Assign second value to shared memory
shared_ints[1] = y;
// Tell child that it can compute the sum now
shared_ints[3] = 1;
// Trap parent in a while-loop while the child
// computes the sum
while(shared_ints[3] == 1);
// Child has completed calculating the sum and
// the parent can print the sum
if(shared_ints[3] == 2) {
printf("The sum is: %d", shared_ints[2]);
printf("\n");
}
} else { // Child code
// Wait for parent to accept input values
while(shared_ints[3] == 0);
// Calculate the sum
shared_ints[2] = shared_ints[0] + shared_ints[1];
// Tell parent sum has been calculated
shared_ints[3] = 2;
/* Child process should finish, so it doesn't fork
and in the upper while loop. this is a fast way to do it */
exit(0);
}
}
在大while循环的每次迭代中,父进程和子进程在此行中调用fork()
:
if((pid = fork()) < 0) {
在每次迭代之后,您将反复产生更多的子进程,并且可能会创建意外的交互。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.