使用共享内存时子进程挂起?

时间:2011-04-14 23:22:11

标签: c linux fork shared-memory

我遇到了一些c代码的非常奇怪的输出。当然,我是c和Linux开发的新手,因为我的背景是围绕.NET和C#。

无论如何,我应该在c中写一个FAT12实现和一个命令shell。只要子进程尝试访问共享内存,我的shell就会挂起。事实上,没有任何事情发生,这真的很奇怪。任何人都可以帮我调试代码吗?

谢谢,

这是运行shell的主循环:

while(strcmp(input, "EXIT") != 0 )
    {
        scanf("%s", input);
        input = String_ToFixedArray(input);

        array = StringArray_Create(input, " "); //split the input string into array.

        if( array->Items == NULL || array->Size == 0 )
        {
            input = "CONTINUE";
            continue;
        }

        if( strcmp(String_ToUpper(array->Items[0]), "PBS") == 0)
        {
            pid_t processId;

            if((processId = fork()) < 0 )
            {
                printf("%s", "Error executing command.");
            }

            //child process. Nothing happens???????
            if( processId == 0 )
            {
                ExecutePBS();
            }
        }
        else if( strcmp(String_ToUpper(array->Items[0]), "PFE") == 0 )
        {
            printf("Execute Print Fat Entries (PFE) Command\n");
        }
        else if( strcmp(String_ToUpper(array->Items[0]), "EXIT") == 0 )
        {
            printf("Exiting..");
            break;
        }
        else
        {
            input = "CONTINUE";
        }

    }

这是一个“驱动程序”功能,它将打印引导扇区(PBS)的内容。问题是无论何时执行此函数,都不会发生任何事情!

void ExecutePBS(void)
{
    int shm_file_id;
    char* shm_file;
    char* shm_file_ptr;
    struct shmid_ds shm_file_buffer;

    if( (shm_file_id = shmget(SHM_FILE_NAME_KEY,SHM_FILE_NAME_SIZE, 0666)) < 0)
    {
        perror("Error locating shared memory segment.");
        exit(1);
    }

    if((shm_file = shmat(shm_file_id, NULL, 0)) == (char *) -1)
    {
        perror("Error attaching shared memory segment to process' scope.");
        exit(1);
    }

    if(shmctl(shm_file_id, IPC_STAT, &shm_file_buffer) == -1 )
    {
        perror("Error while attempting to control the shared memory segment used to store the floppy file name for IPC.");
        exit(1);
    }

    sprintf(shm_file_ptr, "%s", shm_file);

    if( shmdt(shm_file) == -1)
    {
        perror("Error releasing shared memory.");
        exit(1);
    }

    FILE* floppyImage = fopen(shm_file_ptr, "r+");

    if (floppyImage == NULL)
    {
        printf("Could not open the floppy drive or image.\n");
        exit(1);
    }

    BootSector* bootSector = BootSector_ReadBootSector(floppyImage);
    BootSector_ToString(bootSector);

    return;
}

1 个答案:

答案 0 :(得分:4)

不是真正的大问题...但我的理解是它为子进程返回= 0!对于父进程返回= ...所以你应该有两个逻辑,每个情况一个...它代表,在客户端调用该方法之后,它将开始绕过while循环,这是正确的吗?还有......你的意思是“什么都没有”......你试过把printfs用于提高知名度吗?