0

我正在尝试编写一个 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;
}
4

1 回答 1

4
char command1[50], command2[50]; // Added
char *temp[] = {NULL, command1, command2, NULL}; // Modified
temp[0]="sum";
sprintf(temp[1],"%f",x); // remove *
sprintf(temp[2],"%f",y); // remove *

您没有在allocsprint中使用temp[1]temp[2]使用它们作为目标缓冲区,并且在 sprint中sprintf使用不正确。*

您可以使用malloc分配此内存或使用如上示例中所示的其他字符串来初始化数组。


来自Sourav Ghosh的善意评论:

sum.c中,将以下代码行更改为:

if(argc!=3)
{
  printf("error...\n");
  return -1;
}

否则,它可能会导致未定义的行为。

于 2015-03-10T12:20:09.430 回答