Code:
/************************************************
**Brandon Mathis
**Add.cpp v1
**11 Feb 2007
************************************************/
#include <stdio.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
char itoa(int val, int base)
{
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
{
buf[i] = "0123456789abcdef"[val % base];
}
return buf[i+1];
}
int controller(int argc, char *argv[]){
//cout<<"argc: "<< argc<<endl;
pid_t child_pid;
pid_t pid;
int ANSindex=0;
int message;
int messageholder;
int step=1;
char ans[argc];
char x, *ptr_x=&x;
char y, *ptr_y=&y;
char *ptr_null=NULL;
while(step<argc){
ANSindex++;
x=*argv[step++];
if(step==argc){
y='0';
}
else
y=*argv[step++];
cout<<"I will pass "<<*ptr_x<<", "<<*ptr_y<<endl;
pid=fork();
if(pid==-1){
printf("Fork Error\n");
}
if(pid==0){
execlp("./Addworker.o", "./Addworker.o", ptr_x, ptr_y, NULL);
}
else{
child_pid=wait(&message);
if(WIFEXITED(message)){
messageholder=WEXITSTATUS(message);
printf("ANSWER: %d\n", messageholder);
ans[ANSindex]=itoa(messageholder, 10);
cout<<ans[ANSindex]<<" into spot "<<ANSindex<<endl;
}
else
printf("Error in subthread\n");
}
}
cout<<"ans: "<<ans[1]<<" "<<ans[2]<<endl;
//if(ANSindex>1)
// controller(ANSindex+1, ans);
//else return atoi(&ans[1]);
return 0;
}
int main(int argc, char *argv[]){
int index=0;
char deref_argv[argc+1];
// for(index=1; index<argc; index++){
// deref_argv[index]=*argv[index];
// }
printf("%d\n", controller(argc, argv));
return 0;
}
Code:
#include <stdio.h>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
cout<<"Worker Given: "<<*argv[1]<<" "<<*argv[2]<<endl;
int arg1=atoi(argv[1]);
int arg2=atoi(argv[2]);
cout<<"Adding: "<<arg1<<" "<<arg2<<endl;
int x=arg1+arg2;
printf("%d\n", x);
exit(x);
}
==========================
Okay, here is my problem. I want to think that Addworker.c is perfect but when I call the process through execlp() something very odd is happening. It is almost impossible to put this into words
IE:
./Add.o 1 2
will print the debug lines from the Addworker process
Worker Given: 1 2
Adding: 1 21
22
This means that the worker looks at *argv[0] and *argv[1] and sees 1 and 2 in the cout statement
However, atoi() will see argv[0] as 1 and argv[1] as 21
same problem happens when passed two different numbers
passing 3 and 4 causes atoi to see 3 and 43.
Please someone help, this code compiles so perhaps it will be best to just compile it and see how it runs.
Just give Add.c arguments through the command line (End result would be for Add.c to return the sum of all these numbers)