Reputation: 508
I am trying to write an c program which get two float numbers from user and then calls another program with execv() command. But I can't do it , because of converting float to char or I don't know why. The problem is execv() command is not working; the output must be like that
Enter first num: 5
Enter second num: 7
5.000000 + 7.000000 = 12.000000
parentPID: 9745 childPID: 9746 works now
but it is is like that now
Enter first num: 5
Enter second num: 7
parentPID: 9753 childPID: 9754 works now
my first c program 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;
}
and the second program 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;
}
Upvotes: 0
Views: 9301
Reputation: 30489
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 *
You are not alloc
ating to temp[1]
and temp[2]
and using those as destination buffer in sprintf
and using incorrect *
in sprint.
You can use malloc
to allocate this memory or use other string as shown in above example to initialize the array.
From kind comment of Sourav Ghosh:
In sum.c
, change below lines of code to:
if(argc!=3)
{
printf("error...\n");
return -1;
}
or else, it may lead to undefined behaviour.
Upvotes: 5