Advertisement
C0BRA

C++ vs C

Jan 29th, 2014
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. int pty_getproc(lua_State* L)
  2. {
  3.     int fd = lua_tonumber(L, 1);
  4.    
  5.     pid_t pgrp = tcgetpgrp(fd);
  6.     if (pgrp == -1)
  7.         return lua_return(L, nullptr, "failed to locate pid from fd");
  8.    
  9.     std::ifstream ifs("/proc/" + std::to_string(pgrp) + "/cmdline");
  10.    
  11.     if(!ifs.is_open())
  12.         return lua_return(L, nullptr, "failed to open /proc/" + std::to_string(pgrp) + "/cmdline");
  13.    
  14.     std::string contents;
  15.     ifs >> contents;
  16.     ifs.close();
  17.    
  18.     lua_pushstring(L, contents.c_str());
  19.     return 1;
  20. }
  21.  
  22. int c_pty_getproc(lua_State* L)
  23. {
  24.     int fd = lua_tonumber(L, 1);
  25.    
  26.     FILE *f;
  27.     char *path, *buf;
  28.     size_t len;
  29.     int ch;
  30.     pid_t pgrp;
  31.     int r;
  32.  
  33.     if ((pgrp = tcgetpgrp(fd)) == -1)
  34.         return lua_return(L, nullptr, "failed to locate pid from fd");
  35.  
  36.     r = asprintf(&path, "/proc/%lld/cmdline", (long long)pgrp);
  37.     if (r == -1 || path == NULL)
  38.         return lua_return(L, nullptr, "failed to open /proc/$pid/cmdline");
  39.  
  40.     if ((f = fopen(path, "r")) == NULL)
  41.     {
  42.         free(path);
  43.         return lua_return(L, nullptr, "failed to open /proc/$pid/cmdline");
  44.     }
  45.  
  46.     free(path);
  47.  
  48.     len = 0;
  49.     buf = NULL;
  50.     while ((ch = fgetc(f)) != EOF) {
  51.         if (ch == '\0') break;
  52.         buf = (char *)realloc(buf, len + 2);
  53.         if (buf == NULL) return lua_return(L, nullptr, "failed to read file");
  54.         buf[len++] = ch;
  55.     }
  56.  
  57.     if (buf != NULL) {
  58.         buf[len] = '\0';
  59.     }
  60.  
  61.     fclose(f);
  62.    
  63.     lua_pushstring(L, buf);
  64.     return 1;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement