- 论坛徽章:
- 0
|
如何限制同一时刻的fork的最大数量?一定要用共享内存吗?
我修改了一下,但是运行还是不对,不知道哪里错了
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <time.h>;
- #include <unistd.h>;
- #include <sys/types.h>;
- #include <sys/ipc.h>;
- #include <sys/shm.h>;
- main()
- {
- int fknbr = 0;
- key_t key;
- int shmid;
- int ret;
- char *shmbuf;
- key = ftok( "/", 'J' );
- if( key == -1 )
- {
- fprintf( stderr, "ftok() failed!\n" );
- return ;
- }
- shmid = shmget( key, 1024, IPC_CREAT | 0666 );
- if( shmid == -1 )
- {
- fprintf( stderr, "Get shared memory failed!\n" );
- return ;
- }
- shmbuf = NULL;
- shmbuf = shmat( shmid, NULL, 0 );
- if( shmbuf == NULL )
- {
- fprintf( stderr, "Attach shared memory failed!\n" );
- return;
- }
- sprintf( shmbuf, "%d", fknbr );
- fprintf( stderr, "Shared memory writed success![%s]\n", shmbuf );
- ret = shmdt( shmbuf );
- if( ret == -1 )
- {
- fprintf( stderr, "Detach shared memory failed!\n" );
- return;
- }
- for( ; ; )
- {
- shmbuf = shmat( shmid, NULL, SHM_RDONLY );
- if ( shmbuf == NULL )
- {
- fprintf( stderr, "Attach shared memory failed!\n" );
- return;
- }
- fknbr = atoi( shmbuf );
- fprintf( stderr, "Read from shmbuf fknbr=[%d]\n", fknbr );
- ret = shmdt( shmbuf );
- if ( ret == -1 )
- {
- fprintf( stderr, "Detach shared memory failed!\n" );
- return;
- }
- if( fknbr >; 3 )
- {
- printf( "Busy now! fknbr:[%d]\n", fknbr );
- sleep( 5 );
- }
- if( ( fork() == 0 ) && ( fknbr < 4 ) )
- {
- fknbr++;
- printf( "Process fknbr:[%d]\n", fknbr );
- sleep( 3 );
- fknbr--;
- shmbuf = NULL;
- shmbuf = shmat( shmid, NULL, 0 );
- if( shmbuf == NULL )
- {
- fprintf( stderr, "Attach shared memory failed!\n" );
- return;
- }
- sprintf( shmbuf, "%d", fknbr );
- fprintf( stderr, "Shared memory writed success in Process![%s]\n", shmbuf );
- ret = shmdt( shmbuf );
- if( ret == -1 )
- {
- fprintf( stderr, "Detach shared memory failed!\n" );
- return;
- }
- exit( 0 );
- }
- }
- }
复制代码
刚看了看共享内存,抄了一段,好像不太对,不知道哪里错了  |
|