系统相关
首页 > 系统相关> > 使用共享内存时子进程挂起?

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

作者:互联网

我正在从一些C代码中得到一些非常奇怪的输出.当然,我是C和Linux开发的新手,因为我的背景是.NET和C#.

无论如何,我都应该在c中编写FAT12实现和命令外壳.每当子进程尝试访问共享内存时,我的外壳就会挂起.事实上,什么都没有发生,这确实很奇怪.谁能帮我调试代码?

谢谢,

这是运行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;
}

解决方法:

并不是很大的分支……但我的理解是,对于子进程,它返回= 0!对于父进程,它返回= 0 …因此,您应该有两种逻辑,每种情况一种…在客户端调用该方法之后,它也会开始同时在while循环中循环,对吗?还..“什么都没有发生”是什么意思…您是否尝试过放置printfs以增加可见性?

标签:shared-memory,c-3,linux,fork
来源: https://codeday.me/bug/20191102/1993620.html