c - 运行 Bash C 程序时出现 null 错误

标签 c

为什么我在编译时最后得到的 ptr 变量为 null?我试图在程序终止后获取开始时间。输出显示“代码已成功终止”或子进程已成功终止,但末尾的 ptr 变量设置为 null。任何人都可以假设这是为什么吗?

#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<unistd.h>
#include<time.h>
#include<sys/mman.h>
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>

int main(){
  const char *name = "OS";
  long *ptr;
  pid_t childPid;
  childPid = fork();
  int  shm;
  if(childPid == 0){
    char *args[] ={"ls","-l",NULL};
    int shmid;
    int shsize = 5000000;
    key_t key;

    char *s;
    key = 9876;
    if(shmid < 0){
      printf("error getting shmid");
      exit(1);
    }
    shm = shm_open(name,O_CREAT| O_RDWR,0666);
    if(shm == (char *) -1){
      printf("error getting shared memory");
      exit(1);}
    time_t startTime;
    gettimeofday(&startTime,0);
    ptr = (long *) mmap(0,sizeof(startTime),PROT_READ | PROT_WRITE,MAP_SHARED,shm,0);
    ptr+=startTime;
    time_t endTime;
    execvp(args[0],args);
    printf("successfuly created child proceess");
    exit(0);
  }

  else if (childPid <0){
    printf("unsuccessfuly created child proccess");
  }
  else{
    int returnStatus;
    waitpid(childPid,&returnStatus,0);
    if(returnStatus == 0){
      printf("The chiild terminated normally");
      printf("%s",ptr);
      shm_unlink(name);
    }

    if(returnStatus == 1){

      printf("The child terminated with error");
    }
  }

}

最佳答案

您对 ptr 指针的操作方式错误。使用时请使用引用运算符*

这一行:

ptr+=startTime;

应该是

*ptr += 开始时间;

关于c - 运行 Bash C 程序时出现 null 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539405/

相关文章:

c - 如何更改指针字符串中的单个字符?

c - 从旧的 init_timer 到新的 timer_setup 的适配

python - 为什么我的 Python C 扩展会泄漏内存?

c - Windows 7 中 C 的 API 和编译器,主要关注的是

C11相关语言正确性

c# - 如何使用udp从C#客户端与C服务器通信?

找不到位/mathcalls.h

c - 绕过 gdb 中的 ptrace

c - 返回一个用 malloc 分配的字符串?

`recvfrom` 函数可以用来检查之前是否有数据发送到套接字?还是需要积极倾听?