Exemple #1
0
/* finally, the main() function. */
void main()
{
  int sem_set_id;      /* ID of the semaphore set.       */
  union semun sem_val;      /* semaphore value, for semctl(). */
  int child_pid;      /* PID of our child process.      */
  int i;      /* counter for loop operation.    */
  int rc;      /* return value of system calls.  */

  /* create a semaphore set with ID 250, with one semaphore   */
  /* in it, with access only to the owner.                    */
  sem_set_id = semget(SEM_ID, 1, IPC_CREAT | 0600);
  if (sem_set_id == -1) {
    perror("main: semget");
    exit(1);
  }

  /* intialize the first (and single) semaphore in our set to '1'. */
    sem_val.val = 1;
    rc = semctl(sem_set_id, 0, SETVAL, sem_val);
    if (rc == -1) {
      perror("main: semctl");
      exit(1);
    }

    /* create a set of child processes that will compete on the semaphore */
    for (i=0; i<NUM_PROCS; i++) {
      child_pid = fork();
      switch(child_pid) {
      case -1:
	perror("fork");
	exit(1);
      case 0:  /* we're at child process. */
	do_child_loop(sem_set_id, FILE_NAME);
	exit(0);
      default: /* we're at parent process. */
	break;
      }
    }

    /* wait for all children to finish running */
    for (i=0; i<NUM_PROCS; i++) {
      int child_status;

      wait(&child_status);
    }

    printf("main: we're done\n");
    fflush(stdout);
}
Exemple #2
0
	int main(int argc, char **argv)
	{
		int sem_set_id;           //信号灯集的ID
		union semun sem_val;      //信号灯的数值, 用于 semctl()
		int child_pid;            //子进程的进程号
		int i;
		int rc;

		//建立信号灯集, ID是250, 其中只有一个信号灯
		sem_set_id = semget(SEM_ID, 1, IPC_CREAT | 0600);
		if (sem_set_id == -1) {
			perror("main: semget");
			exit(1);
		}

		//把第一个信号灯的数值设置为1
		sem_val.val = 1;
		rc = semctl(sem_set_id, 0, SETVAL, sem_val);
		if (rc == -1) {
			perror("main: semctl");
			exit(1);
		}

		//建立一些子进程, 使它们可以同时以竞争的方式访问信号灯
		for (i=0; i<NUM_PROCS; i++) {
			child_pid = fork();
			switch(child_pid) {
				case -1:
					perror("fork");
					exit(1);
				case 0:		//子进程
					do_child_loop(sem_set_id, FILE_NAME);
					exit(0);
				default:	//父进程接着运行
					break;
			}
		}

		//等待子进程结束
		for (i=0; i<NUM_PROCS; i++) {
			int child_status;
			wait(&child_status);
		}

		printf("main: we're done\n");
		fflush(stdout);
		return 0;
	}