我正在尝试编写一个 c 程序,它从用户那里获取两个浮点数,然后使用 execv() 命令调用另一个程序。但我不能这样做,因为将 float 转换为 char 或者我不知道为什么。问题是 execv() 命令不起作用;输出必须是这样的
输入第一个数字:5
输入第二个数字:7
5.000000 + 7.000000 = 12.000000
parentPID:9745 childPID:9746 现在可以使用
但现在就是这样
输入第一个数字:5
输入第二个数字:7
parentPID:9753 childPID:9754 现在可以使用
我的第一个 c 程序 sum.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if(argc!=3)
printf("error...\n");
double a=atof(argv[1]);
double b=atof(argv[2]);
printf("%lf + %lf = %lf \n",a,b,a+b);
return 0;
}
第二个程序calculate.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
float x,y;
pid_t pid;
printf("Enter first num: ");
scanf("%f",&x);
printf("Enter second num: ");
scanf("%f",&y);
if((pid=fork())== -1)
{
printf("can not fork..\n");
exit(1);
}
if(pid==0) //child
{
pid=getpid();
char *temp[] = {NULL,NULL,NULL,NULL};
temp[0]="sum";
sprintf(*temp[1],"%f",x); //here I want to convert float number to char but it doesn't work
sprintf(*temp[2],"%f",y);
execv("sum",temp);
}
else
{
wait(NULL);
printf("parentPID: %d childPID: %d works now.\n", getpid(), pid);
}
return 0;
}