473,387 Members | 3,750 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Linux programme - different results each run

Hi i have got quite strange problem. I wrote programme which shows all
runnign processes. This info is get from /proc dir. When a dir that is
process dir is found stat file is read and pid, name and state are get
from it. The thing is that on my machine every time I run it, it gives
different results. Sometimes it shows nothing - most of the times.
Sometimes it shows info about 4 processes. Sometimes it works
correctly. I don't now whats wrong, I 've tried to find the mistake,
but I could'n. I begginer programmer and I don't know how to cope with
this problem. Please help me!

Here is the code:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. #include <stdio.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <string.h>
  7. #include <dirent.h>
  8. #include <stdlib.h>
  9.  
  10. int isNum(char );
  11. int isProcDir(char * );
  12. int showRunningProcesses();
  13.  
  14. int main()
  15. {
  16.  
  17. showRunningProcesses();
  18.  
  19. return 0;
  20.  
  21. }
  22.  
  23. /*
  24.  
  25. Function indicates if char given in data variable is number.
  26. If it is it returns 0. If it is not a number it returns 1.
  27.  
  28. */
  29. int isNum(char data)
  30. {
  31.  
  32. switch(data)
  33. {
  34. case '0': return 0;
  35. case '1': return 0;
  36. case '2': return 0;
  37. case '3': return 0;
  38. case '4': return 0;
  39. case '5': return 0;
  40. case '6': return 0;
  41. case '7': return 0;
  42. case '8': return 0;
  43. case '9': return 0;
  44. default : return 1;
  45. }
  46.  
  47. }
  48.  
  49. /*
  50.  
  51. Function indicates if char given by *path pointer
  52. is process dir (in /proc file system). If it is it
  53. returns 0. If it is not it returns 1.
  54.  
  55. */
  56.  
  57. int isProcDir(char *path)
  58. {
  59. struct stat st;
  60. int i;
  61. int path_length;
  62.  
  63. lstat(path, &st);
  64. path_length = strlen(path);
  65.  
  66. //printf("running.. %s\n", path);
  67. //printf("%o", st.st_mode);
  68. if (S_ISDIR(st.st_mode))
  69. return 1;
  70. else if(S_ISLNK(st.st_mode))
  71. return 1;
  72. else if(S_ISCHR(st.st_mode))
  73. return 1;
  74. else if(S_ISBLK(st.st_mode))
  75. return 1;
  76. else if(S_ISFIFO(st.st_mode))
  77. return 1;
  78. else if(S_ISSOCK(st.st_mode))
  79. return 1;
  80. else if(S_ISREG(st.st_mode))
  81. return 1;
  82. else
  83. {
  84. //printf("path: %s \n", path);
  85. //fprintf(stderr, "found");
  86.  
  87.  
  88. for(i=0; i<path_length; i++)
  89. {
  90. if (isNum(path[i]))
  91. {
  92. return 1;
  93. }
  94. }
  95.  
  96. return 0;
  97. }
  98.  
  99. }
  100.  
  101. int showRunningProcesses()
  102. {
  103.  
  104. int i;
  105. DIR *directory, *process_directory;
  106. FILE *fp;
  107. struct dirent *dir_entry;
  108. char *path = (char *)malloc(50);
  109. char *name;
  110. char pid[10], procName[15], state[5];
  111.  
  112. strcat(path,"/proc/");
  113.  
  114. if( ( directory=opendir(path) ) == NULL )
  115. {
  116. fprintf(stderr,    "Couldn't open /proc dir.");
  117. return 1;
  118.  
  119. }
  120.  
  121. while(dir_entry=readdir(directory))
  122. {
  123.  
  124. /*
  125. Check if read directory is process
  126. directory.
  127. */
  128.  
  129. if( !( isProcDir(dir_entry->d_name) ) )
  130. {
  131.  
  132. //printf("running..");
  133.  
  134. /*
  135. A process directory was found.
  136. */
  137.  
  138. /*
  139. Add to path variable name of the
  140. process directory and then add "/"
  141. to make path correct.
  142. */
  143. strcat(path, dir_entry->d_name);
  144. strcat(path,"/");
  145.  
  146. //printf("%s\n", path);
  147.  
  148. if ( (process_directory=opendir(path) ) == NULL)
  149. {
  150. printf("Couldn't open process directory.");
  151. return 1;
  152. }
  153. else
  154. {
  155. strcat(path,"stat");
  156.  
  157. if ( ( fp=fopen(path,"r") ) == NULL)
  158. {
  159. printf("Couldn't open process stat file.");
  160. return 1;
  161. }
  162. else
  163. {
  164. fscanf(fp,"%s", &pid);
  165. printf("PID: %s",pid);
  166. fscanf(fp,"%s", &procName);
  167. printf("\t\tName: %s", procName);
  168. fscanf(fp,"%s", &state);
  169. printf("\t\tState: %s\n", state);
  170.  
  171. fclose(fp);
  172. }
  173.  
  174. }
  175.  
  176. closedir(process_directory);
  177.  
  178. strcpy(path,"");
  179. strcat(path,"/proc/");
  180.  
  181. }
  182.  
  183. }
  184.  
  185. closedir(directory);
  186.  
  187. }
  188.  
  189.  
Thank you,
John

Dec 11 '05 #1
5 1750
ul****@autograf.pl writes:
Hi i have got quite strange problem. I wrote programme which shows all
runnign processes. This info is get from /proc dir. When a dir that is
process dir is found stat file is read and pid, name and state are get
from it. The thing is that on my machine every time I run it, it gives
different results. Sometimes it shows nothing - most of the times.
Sometimes it shows info about 4 processes. Sometimes it works
correctly. I don't now whats wrong, I 've tried to find the mistake,
but I could'n. I begginer programmer and I don't know how to cope with
this problem. Please help me!
This is Linux-specific and off-topic in comp.nlag.c. Try
comp.os.linux.programmer.

A few things did jump out at me:
int main()
{

showRunningProcesses();

return 0;

}
showRunningProcesses() returns an int; you ignore the result.
/*

Function indicates if char given in data variable is number.
If it is it returns 0. If it is not a number it returns 1.

*/
int isNum(char data)
{

switch(data)
{
case '0': return 0;
case '1': return 0;
case '2': return 0;
case '3': return 0;
case '4': return 0;
case '5': return 0;
case '6': return 0;
case '7': return 0;
case '8': return 0;
case '9': return 0;
default : return 1;
}

}
This is backwards; logically, it should return 0 for false, 1 for
true. Names starting with "is" and a lowercase letter are reserved;
"is_Num" or "is_num" would be ok. And there's already a function that
does exactly what you want: isdigit(), declared in <ctype.h>.
/*

Function indicates if char given by *path pointer
is process dir (in /proc file system). If it is it
returns 0. If it is not it returns 1.

*/
int isProcDir(char *path)
Some of the same comments as above apply here.
{
struct stat st;
int i;
int path_length;

lstat(path, &st);
path_length = strlen(path);

//printf("running.. %s\n", path);
//printf("%o", st.st_mode);
if (S_ISDIR(st.st_mode))
return 1;
else if(S_ISLNK(st.st_mode))
return 1;
else if(S_ISCHR(st.st_mode))
return 1;
else if(S_ISBLK(st.st_mode))
return 1;
else if(S_ISFIFO(st.st_mode))
return 1;
else if(S_ISSOCK(st.st_mode))
return 1;
else if(S_ISREG(st.st_mode))
return 1;
else
{
//printf("path: %s \n", path);
//fprintf(stderr, "found");
for(i=0; i<path_length; i++)
{
if (isNum(path[i]))
{
return 1;
}
}

return 0;
}

}

int showRunningProcesses()
{

int i;
DIR *directory, *process_directory;
FILE *fp;
struct dirent *dir_entry;
char *path = (char *)malloc(50);
char *name;
char pid[10], procName[15], state[5];

strcat(path,"/proc/");

if( ( directory=opendir(path) ) == NULL )
{
fprintf(stderr, "Couldn't open /proc dir.");
return 1;

}

while(dir_entry=readdir(directory))
{

/*
Check if read directory is process
directory.
*/

if( !( isProcDir(dir_entry->d_name) ) )
{

//printf("running..");

/*
A process directory was found.
*/

/*
Add to path variable name of the
process directory and then add "/"
to make path correct.
*/
strcat(path, dir_entry->d_name);
strcat(path,"/");

//printf("%s\n", path);

if ( (process_directory=opendir(path) ) == NULL)
{
printf("Couldn't open process directory.");
return 1;
}
else
{
strcat(path,"stat");

if ( ( fp=fopen(path,"r") ) == NULL)
{
printf("Couldn't open process stat file.");
return 1;
}
else
{
fscanf(fp,"%s", &pid);
printf("PID: %s",pid);
fscanf(fp,"%s", &procName);
printf("\t\tName: %s", procName);
fscanf(fp,"%s", &state);
printf("\t\tState: %s\n", state);

fclose(fp);
}

}

closedir(process_directory);

strcpy(path,"");
strcat(path,"/proc/");

}

}

closedir(directory);

}

[/code]

Thank you,
John


--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 11 '05 #2
I'm not a linux programmer, but I found one thing that can make things
not work.

ul****@autograf.pl wrote:
Hi i have got quite strange problem. I wrote programme which shows all
runnign processes. This info is get from /proc dir. When a dir that is
process dir is found stat file is read and pid, name and state are get
from it. The thing is that on my machine every time I run it, it gives
different results. Sometimes it shows nothing - most of the times.
Sometimes it shows info about 4 processes. Sometimes it works
correctly. I don't now whats wrong, I 've tried to find the mistake,
but I could'n. I begginer programmer and I don't know how to cope with
this problem. Please help me!

Here is the code:

Expand|Select|Wrap|Line Numbers
  1.  #include <stdio.h>
  2.  #include <sys/types.h>
  3.  #include <sys/stat.h>
  4.  #include <string.h>
  5.  #include <dirent.h>
  6.  #include <stdlib.h>
  7.  int isNum(char );
  8.  int isProcDir(char * );
  9.  int showRunningProcesses();
  10.  int main()
  11.  {
  12.      showRunningProcesses();
  13.      return 0;
  14.  }
  15.  /*
  16.  Function indicates if char given in data variable is number.
  17.  If it is it returns 0. If it is not a number it returns 1.
  18.  */
  19.  int isNum(char data)
  20.  {
  21.      switch(data)
  22.      {
  23.          case '0': return 0;
  24.          case '1': return 0;
  25.          case '2': return 0;
  26.          case '3': return 0;
  27.          case '4': return 0;
  28.          case '5': return 0;
  29.          case '6': return 0;
  30.          case '7': return 0;
  31.          case '8': return 0;
  32.          case '9': return 0;
  33.          default : return 1;
  34.      }
  35.  }
  36.  /*
  37.  Function indicates if char given by *path pointer
  38.  is process dir (in /proc file system). If it is it
  39.  returns 0. If it is not it returns 1.
  40.  */
  41.  int isProcDir(char *path)
  42.  {
  43.      struct stat st;
  44.      int i;
  45.      int path_length;
  46.      lstat(path, &st);
  47.      path_length = strlen(path);
  48.      //printf("running.. %s\n", path);
  49.      //printf("%o", st.st_mode);
  50.      if (S_ISDIR(st.st_mode))
  51.          return 1;
  52.      else if(S_ISLNK(st.st_mode))
  53.          return 1;
  54.      else if(S_ISCHR(st.st_mode))
  55.          return 1;
  56.      else if(S_ISBLK(st.st_mode))
  57.          return 1;
  58.      else if(S_ISFIFO(st.st_mode))
  59.          return 1;
  60.      else if(S_ISSOCK(st.st_mode))
  61.          return 1;
  62.      else if(S_ISREG(st.st_mode))
  63.          return 1;
  64.      else
  65.      {
  66.          //printf("path: %s \n", path);
  67.          //fprintf(stderr, "found");
  68.          for(i=0; i<path_length; i++)
  69.          {
  70.              if (isNum(path[i]))
  71.              {
  72.                  return 1;
  73.              }
  74.          }
  75.          return 0;
  76.      }
  77.  }
  78.  int showRunningProcesses()
  79.  {
  80.      int i;
  81.      DIR *directory, *process_directory;
  82.      FILE *fp;
  83.      struct dirent *dir_entry;
  84.      char *path = (char *)malloc(50);
  •  
  • If this is C code, you don't need to cast the return value of malloc.
  • And since you never change the size of the buffer, you can just do this
  • instead, and then you can remove the first strcat or strcpy too:
  •  
  • char path[50] = "/proc/";
  •      char *name;
  •      char pid[10], procName[15], state[5];
  •      strcat(path,"/proc/");
  •  
  • strcat won't work on uninitialized strings, use strcpy instead.
  •      if( ( directory=opendir(path) ) == NULL )
  •      {
  •          fprintf(stderr,    "Couldn't open /proc dir.");
  •          return 1;
  •      }
  •      while(dir_entry=readdir(directory))
  •      {
  •          /*
  •          Check if read directory is process
  •          directory.
  •          */
  •          if( !( isProcDir(dir_entry->d_name) ) )
  •          {
  •          //printf("running..");
  •          /*
  •          A process directory was found.
  •          */
  •          /*
  •          Add to path variable name of the
  •          process directory and then add "/"
  •          to make path correct.
  •          */
  •          strcat(path, dir_entry->d_name);
  •          strcat(path,"/");
  •          //printf("%s\n", path);
  •          if ( (process_directory=opendir(path) ) == NULL)
  •          {
  •              printf("Couldn't open process directory.");
  •              return 1;
  •          }
  •          else
  •          {
  •              strcat(path,"stat");
  •              if ( ( fp=fopen(path,"r") ) == NULL)
  •              {
  •                  printf("Couldn't open process stat file.");
  •                  return 1;
  •              }
  •              else
  •              {
  •                  fscanf(fp,"%s", &pid);
  •                  printf("PID: %s",pid);
  •                  fscanf(fp,"%s", &procName);
  •                  printf("\t\tName: %s", procName);
  •                  fscanf(fp,"%s", &state);
  •                  printf("\t\tState: %s\n", state);
  •                  fclose(fp);
  •              }
  •          }
  •          closedir(process_directory);
  •          strcpy(path,"");
  •          strcat(path,"/proc/");
  •  
  • strcpy(path,"") is the same as doing path = '\0'.  Even better, just
  • delete that line, and just do strcpy(path,"/proc/"). You could also do
  • path[6] = '\0' instead.
  •          }
  •      }
  •      closedir(directory);
  •  }
  •  

  • Thank you,
    John
    Dec 11 '05 #3
    There is nothing wrong with ignoring the result of a function. That has
    no effect whatsoever in the resulting behavior of a program, provided
    it was intentionally desgined to do so.

    Dec 11 '05 #4
    "ms******@gmail.com" <ms******@gmail.com> writes:
    There is nothing wrong with ignoring the result of a function. That has
    no effect whatsoever in the resulting behavior of a program, provided
    it was intentionally desgined to do so.


    Please read <http://cfaj.freeshell.org/google/> and follow its advice.

    Whether ignoring the result of a function is an error depends on the
    circumstances. In the posted program, the function
    showRunningProcesses() is declared to return an int, and in fact it
    returns a value of 1 to indicate an error. It doesn't make sense to
    do that and then ignore the result in the only place it's called.

    Something else I just noticed is that, though it returns 1 to indicate
    an error, it just falls off the end if there's no error. If it
    succeeds, an attempt to use the returned value will invoke undefined
    behavior. The solution is to explicitly "return 0;" on success.

    The main program should probably do an "exit(EXIT_SUCCESS);" if the
    function succeeds, and an "exit(EXIT_FAILURE);" if it fails.

    --
    Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
    We must do something. This is something. Therefore, we must do this.
    Dec 11 '05 #5
    Delete S_ISDIR(st.st_mode)) .

    Dec 12 '05 #6

    This thread has been closed and replies have been disabled. Please start a new discussion.

    Similar topics

    3
    by: XMLSDK | last post by:
    I have written a programme to receive the HTML code from a URL http://www.pru.com.hk/ But I dunno why it doesn't work. It can only receive the beginning few lines: <!-- i n clude file="BB.asp"...
    12
    by: Mike Dee | last post by:
    A very very basic UTF-8 question that's driving me nuts: If I have this in the beginning of my Python script in Linux: #!/usr/bin/env python # -*- coding: UTF-8 -*- should I - or should I...
    23
    by: Rudolf Bargholz | last post by:
    Hi, I have a ralatively simple SQL: select FK from TABLE where upper(A) like 'B%' and upper(C) like 'D%' We have DB2 UDB v7.1 FP 12 installed on Linux and on Windows 2003 On Linux using...
    1
    by: gassara | last post by:
    salut ; Nous sommes un groupe d'etudiant de l'INSAT de la Tunisie.Notre filiere est Génie Logiciel, nous réalisons un Mini projet concernant la configuration et l'administration de DB2 (V...
    2
    by: micmic | last post by:
    Dear all experts, As i found in the internet, there is a C# programme that can make use of the resource manager to choose different lanugage string for particular expression using resource...
    17
    by: Jim Strickland | last post by:
    We currently are running a data intensive web service on a Mac using 4D. The developers of our site are looking at converting this web service to PostgreSQL. We will have a backup of our three...
    4
    by: Frank Potter | last post by:
    I want to search something by a key word from inside my py script. The using google idea comes to my mind first because write a search programme from scratch is not so easy. I want to take...
    15
    by: Joe Weinstein | last post by:
    Hi. Below is a simple JDBC program to insert and extract a numerical value. When ResultSet.getDouble() is called, the same program produces different output on solaris than it does on Linux. I...
    1
    by: deborahb | last post by:
    On a linux Red Hat Enterprise Linux AS release 4 (Nahant Update 5) box, I've installed DB2 V9 Client at the fixpak3 level. The install was successfull but 2 additional log files were produced with...
    0
    by: taylorcarr | last post by:
    A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
    0
    by: Charles Arthur | last post by:
    How do i turn on java script on a villaon, callus and itel keypad mobile phone
    0
    by: aa123db | last post by:
    Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
    0
    by: ryjfgjl | last post by:
    If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
    0
    by: ryjfgjl | last post by:
    In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
    0
    by: emmanuelkatto | last post by:
    Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
    1
    by: nemocccc | last post by:
    hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
    1
    by: Sonnysonu | last post by:
    This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
    0
    by: Hystou | last post by:
    Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

    By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

    To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.