如何使用execl将指针作为命令行参数发送到另一个程序
我试图接受两个整数(例如低和高)作为命令行参数,在我的主要程序中,我试图调用其他两个程序。 program-1应计算出(低,高)在sum_res和program-2之间的所有整数的汇总,应评估sum_res是否为prime。
因此,我试图创建两个过程,并且想在两个过程之间共享一个共同的变量,但是在执行后,我检查了我只有主要程序才给我分段故障。
我是Execl概念的新手,请帮助:
我的主要程序:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
int sum_res=0;
int main(int argc, char *argv[])
{
int low = atoi(argv[1]), high = atoi(argv[2]);
pid_t pid;
if((pid=vfork())==0)
{
execl("pro1","pro1", low, high, &sum_res, (char *)NULL);
exit(0);
}
else if(pid > 0)
{
wait(NULL);
execl("pro2","pro2", sum_res, (char *)NULL);
exit(0);
}
return 0;
}
我的Program -1是:(命名为Prog1.c,并编译为GCC -G Prog1.c -o Prog1)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int n1 = atoi(argv[1]), n2 = atoi(argv[2]), i, sum_res = (int *)(argv[3]);
for(i=n1; i<=n2; i++)
{
(*sum_res)+=i;
}
printf("Sum is : %d\n", *sum_res);
return 0;
}
我的Program -2是:(命名prog2.c并以gcc -g prog2.c -o prog2 -lm的汇编,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int *main(int argc, char *argv[])
{
int sum_res = atoi(argv[1]), i, c=0;
for(i=2; i<=sqrt(sum_res); i++)
{
if(sum_res % i == 0)
{
c++;
break;
}
}
if(c==0)
{
printf("Prime \n");
}
else printf("Not Prime \n");
return 0;
}
注意:所有3个程序及其各自的可执行文件都存在于相同的当前工作目录中。
如果这是不可能的,那么我将如何将program-1的总和到program-2中?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会收到细分故障是有道理的。指针是单个过程内存空间内的内存地址。每个过程存储空间都是完全独立的,并且是分开的。这样可以防止一个程序不小心打破另一个程序。当您尝试在过程地址空间(过程中的内存“细分”)之外读取或写入时,您会收到分段故障。
如果要在两个过程之间共享内存空间,则需要使用IPC(过程间通信)库来启用内存空间。一种方法是
shm_open
函数:It makes sense that you receive a segmentation fault. A pointer is a memory address inside a single process memory space. Each process memory space is completely independent and separated. This prevents one programs from accidentally breaking another program. When you try to read or write outside your process address space (the memory "segment" for your process) you receive a segmentation fault.
If you want to share memory space between two processes you need to use an IPC (Inter-process Communication) libraries to enable sharing memory space. One way is the
shm_open
function: https://www.geeksforgeeks.org/posix-shared-memory-api/