I'm writing a code, which is supposed to work with child processes, using different ways to send parameters. However, the problem doesn't concern this part. I have a menu with options, which specify the way, a user can deal with child processes. Depending on a selected option, a certain case should be chosen to work. It doesn't work the way it should, here goes the code and output, which will explain the problem better, than I can.
P.S. Sorry for possible mistakes, hopefully someone can help me out.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <locale.h>
#include <string.h>
#include <math.h>
extern char **environ;
int main(int argc, const char *argv[], char *env[])
{
char **name;
int x = 0, num;
pid_t pid;
for(num=0; ; num++) //counts the number of environment parameters
if(env[num] == NULL)
break;
name = (char **) calloc(1, sizeof(char *));
if(!name)
{
printf("\nMemory isn't allocated");
return -1;
}
name[0] = (char *) calloc(9, sizeof(char));
if(!name[0])
{
printf("\nMemory isn't allocated");
return -1;
}
for(int i=0; i<num; i++)
fprintf(stdout, "%s\n", args[i]);
fprintf(stdout, "Parent process's started...\n");
char *temp;
temp = (char *) calloc(12, sizeof(char));
if(!temp)
{
printf("\nMemory isn't allocated");
return -1;
}
while(x < 100)
{
sprintf(temp, "%d", x);
strcpy(name[0], "child_");
strcat(name[0], temp);
puts("path info: +-using getenv()");
puts(" *-scanning array of environment parameters");
puts(" &-using environ");
puts(" q-end");
fflush(stdin);
switch(getchar())
{
case '+':
printf("PLUS:\n");
pid = fork();
if(pid == -1)
{
fprintf(stdout, "Error, code - %d\n", errno);
}
else
{
execve("./child", name, env);
}
break;
case '*':
printf("ASTERISK\n");
pid = fork();
if(pid == -1)
{
fprintf(stdout, "Error, code - %d\n", errno);
}
else
{
execve(findPath(env, num), name, env);
}
break;
case '&':
printf("AMPERSAND:\n");
pid = fork();
if(pid == -1)
{
fprintf(stdout, "Error, code - %d\n", errno);
}
else
{
execve(findPath(environ, num), name, env);
}
break;
case 'q':
return 0;
default:
printf("Wrong parameter\n");
return -1;
}
x++;
}
exit(0);
}
The output is the following:
Parent process's started...
path info: +-using getenv()
*-scanning array of environment parameters
&-using environ
q-end
+
PLUS:
path info: +-using getenv()
*-scanning array of environment parameters
&-using environ
q-end
path info: +-using getenv()
*-scanning array of environment parameters
&-using environ
q-end
q
Program ended with exit code: 0
Meanwhile, it's supposed to be like this:
Parent process's started...
path info: +-using getenv()
*-scanning array of environment parameters
&-using environ
q-end
+
PLUS:
path info: +-using getenv()
*-scanning array of environment parameters
&-using environ
q-end
q
Program ended with exit code: 0