Project

General

Profile

Statistics
| Revision:

root / branches / simulator / projects / simulator / simulator / core / main.c @ 984

History | View | Annotate | Download (2.09 KB)

1
#include "gtk_gui.h"
2
#include <stdio.h>
3
#include <unistd.h>
4
#include <stdlib.h>
5
#include <signal.h>
6
#include <sys/wait.h>
7
#include <robot_shared.h>
8
#include <sys/ipc.h>
9
#include <sys/types.h>
10
#include <sys/shm.h>
11
#include <errno.h>
12

    
13
int create_robot(char *execname, int id, SimulatorRobot* sim_memory)
14
{
15
  /* do shared memory stuff here */
16
  key_t key = IPC_PRIVATE;
17
  /*Memory accessible only to children and gives them read/write priveledge*/
18
  sim_memory->robotSharedMemoryID = shmget(key, sizeof(RobotShared), IPC_CREAT | 0666);
19
  
20
  if(sim_memory->robotSharedMemoryID < 0)
21
  {
22
          printf("error getting shared memory\n");
23
          return -1;
24
  }
25

    
26
  sim_memory->robotState = shmat(sim_memory->robotSharedMemoryID, NULL, 0);
27
  
28
  if(!(sim_memory->robotState))
29
  {
30
        printf("error attaching parent process\n");
31
        return -1;
32
  }
33
  
34
  /*Init robot structure here*/
35
  sim_memory->robotState->motor1 = 0;
36
  sim_memory->robotState->motor2 = 0;
37

    
38
  int pid;
39

    
40
  if((pid = fork())<0){
41
    printf("error with fork!\n");                        
42
    return -1;
43
  }                       
44
  
45
  char var[21];
46
  sprintf(var, "memory_id=%d", sim_memory->robotSharedMemoryID);
47
  char *envp[] = {var, NULL};
48

    
49
  if(!pid){
50
    /* restore default sigchld handler */
51
    signal(SIGCHLD, SIG_DFL);
52

    
53
    execve(execname, NULL, envp);  //TODO: keep the other env. stuff around
54
    printf ("error! exec failed\n");
55
        
56
    exit(-1);
57
  }
58
                   
59
  return pid;
60
}
61

    
62
int free_robot(SimulatorRobot sim)                       
63
{
64
        shmdt(sim.robotState);
65
        return shmctl(sim.robotSharedMemoryID, IPC_RMID, NULL); 
66
}
67

    
68
void *sig_chld_handler(int sig)
69
{
70
  pid_t pid;
71
  int cstat;
72

    
73
  printf("SIGCHLD: parent waiting\n");
74

    
75
  pid = waitpid(0, &cstat, WUNTRACED);
76

    
77
  printf("got %d from %d\n", cstat, pid);
78

    
79
  kill(pid, SIGCONT);
80

    
81
  return NULL;
82
}
83

    
84
int main(int argc, char** argv)
85
{
86
  signal(SIGCHLD, sig_chld_handler);
87

    
88
  SimulatorRobot sim;
89

    
90
  create_robot("robot_test/robot", 0, &sim);
91

    
92
  printf("returned to parent\n");
93

    
94
  int x;
95
  for(x = 0; x <10000; x++)
96
          printf("motor 1: %d\n", x);
97

    
98
  gtk_gui_run(argc, argv);
99

    
100
  printf("parent exiting.\n");
101

    
102
  return 0;
103
}
104