code review: read in ps(1) result

/*thank you for your time*/

/*read in ps(1) result*/

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>

#define M 256
#define N 32

#define str(n) #n /*from pete's*/
#define xstr(n) str(n)

int main(void)
{
    char uid[N + 1];
    pid_t pid;
    pid_t ppid;
    char stime[N + 1];
    char cmd[M + 1];
    char *ps = "ps -ef";
    FILE *fp;
    int errnum;
    int n;

    errno = 0;
    if (!(fp = popen(ps, "r"))){
        errnum = errno;
        fprintf(stderr, "%s\n", strerror(errnum));
        return 1;
    }
    errno = 0;
    while((n = fscanf(fp, "%"xstr(N)"s %d %d %*s "
            "%"xstr(N)"s %*s %*s %"xstr(M)"[^\n]",
            uid, &pid, &ppid, stime, cmd)) != EOF){
        if (n != 5){
            fscanf(fp, "%*[^\n]");
        continue;
        }
        fprintf(stdout, "%s, %d, %d, %s, %s\n",
        uid, (int)pid, (int)ppid, stime, cmd);
        errno = 0;
    }
    errnum = errno;
    if (errnum)
        fprintf(stderr, "%s\n", strerror(errnum));
    pclose(fp);
    return 0
}
0
7/16/2010 12:44:31 PM
comp.lang.c 29886 articles. 34 followers. spinoza1111 (3247) is leader. Post Follow

7 Replies
250 Views

Similar Articles

[PageSpeed] 53
lovecreatesbea...@gmail.com ha scritto:

> #include<stdio.h>
> #include<errno.h>
> #include<sys/types.h>
>          fprintf(stderr, "%s\n", strerror(errnum));

you should #include <string.h>, this header
contains the strerror's prototype

>      return 0

and append a semicolon ";" to this line


-- 
Vincenzo Mercuri
0
Vincenzo
7/16/2010 1:33:39 PM
On 7/16/2010 8:44 AM, lovecreatesbea...@gmail.com wrote:
> [...]
>      errno = 0;
>      [...]
>      errnum = errno;
>      if (errnum)
>          fprintf(stderr, "%s\n", strerror(errnum));

     No.  Except as specifically documented (e.g., for strtod()),
any library function can set `errno' to a non-zero value, even
if no error occurs.  Thus, finding `errno != 0' does not mean
there has been an error.  Also, only a few library functions are
obliged to set `errno' when an error occurs -- for example, a
failing fopen() is not required to set it -- so `errno == 0' does
not imply the absence of errors.  You have to detect success/failure
by other means, and then (perhaps) consult `errno' for further
information about a failure.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
0
Eric
7/16/2010 6:18:30 PM
Eric Sosman <esosman@ieee-dot-org.invalid> writes:
> On 7/16/2010 8:44 AM, lovecreatesbea...@gmail.com wrote:
>> [...]
>>      errno = 0;
>>      [...]
>>      errnum = errno;
>>      if (errnum)
>>          fprintf(stderr, "%s\n", strerror(errnum));
>
>      No.  Except as specifically documented (e.g., for strtod()),
> any library function can set `errno' to a non-zero value, even
> if no error occurs.  Thus, finding `errno != 0' does not mean
> there has been an error.  Also, only a few library functions are
> obliged to set `errno' when an error occurs -- for example, a
> failing fopen() is not required to set it -- so `errno == 0' does
> not imply the absence of errors.  You have to detect success/failure
> by other means, and then (perhaps) consult `errno' for further
> information about a failure.

To expand on that a bit, some secondary standards may specify that
certain standard C functions must set errno on failure.  For example,
POSIX requires fopen() to set errno to one of several values (none
of which are defined by the C standard).  And I don't know of any
C implementations, POSIX or otherwise, in which fopen() *doesn't*
set errno to some sensible value on failure (but my experience
is sufficiently limited that I probably wouldn't know about them
anyway).

If you're only concerned with POSIX-compliant systems, you can assume
that the value of errno is meaningful after a call to fopen() --
but *only* if you set errno to 0 before the call *and* fopen()
reported failure by returning a null pointer (otherwise errno
could be set to some spurious value, either by previous code or by
something called internally by fopen().

For non-POSIX systems, you can *probably* assume that errno is
meaningful under the above circumstances (and perror() and/or
strerror() will give you a useful message), but that's not at all
guaranteed by the C standard.

Note that the only errno values specified by the C standard itself
are 0, EDOM, EILSEQ, and ERANGE.  Anything beyond that is left to
secondary standards and to individual implementations.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
0
Keith
7/16/2010 7:30:03 PM
Keith Thompson <kst-u@mib.org> writes:

> To expand on that a bit, some secondary standards may specify that
> certain standard C functions must set errno on failure.  For example,
> POSIX requires fopen() to set errno to one of several values (none
> of which are defined by the C standard).  And I don't know of any
> C implementations, POSIX or otherwise, in which fopen() *doesn't*
> set errno to some sensible value on failure (but my experience
> is sufficiently limited that I probably wouldn't know about them
> anyway).

malloc() may be a better example.  POSIX requires malloc() to set
errno to ENOMEM on failure, if memory is not available.  But a
lot of non-POSIX implementations in fact do not do this (and
ENOMEM is not defined by ISO C).
-- 
Ben Pfaff 
http://benpfaff.org
0
Ben
7/16/2010 8:11:25 PM
On Fri, 16 Jul 2010 12:30:03 -0700, Keith Thompson wrote:

> Note that the only errno values specified by the C standard itself
> are 0, EDOM, EILSEQ, and ERANGE.  Anything beyond that is left to
> secondary standards and to individual implementations.

That should provide a clue as to which functions are required (by the C
standard) to set errno under some circumstances (hint: not many of them).

errno is basically a POSIX feature which managed to leak into the C
standards. POSIX itself defines 81 possible non-zero values for errno,
while Linux currently defines 129 (1 through 131, with 41 and 58 unused).

http://www.opengroup.org/onlinepubs/9699919799/basedefs/errno.h.html


0
nobody (5159)
7/16/2010 8:40:46 PM
lovecreatesbea...@gmail.com wrote:
 
> #define str(n) #n /*from pete's*/
> #define xstr(n) str(n)

You can search for "xstr" in the C standard.
That's where I got those macros from.

-- 
pete
0
pete
7/16/2010 10:14:15 PM
Keith Thompson <kst-u@mib.org> wrote:
> 
> And I don't know of any
> C implementations, POSIX or otherwise, in which fopen() *doesn't*
> set errno to some sensible value on failure

Traditional Unix implementations didn't explicitly set errno but most
fopen() failures are caused by the failure of an underlying system call
which does, so it works in most cases.  But not all: there were some
obscure failure modes that left errno set to a nonsensical value.
-- 
Larry Jones

Any game without push-ups, hits, burns or noogies is a sissy game. -- Calvin
0
lawrence
7/27/2010 3:38:54 PM
Reply:
Similar Artilces:

Date code
I am experiencing a little trouble with some code for a date field. I want a message box to appear to inform me that I have less than 6-months dating on an item when someone enters in the receipt document; Expiration Date field. I am using the below code but keep getting an error. Any thoughts? If [txtExpirationDate] <= Now( ) + Month (6) Then MsgBox(“Expiration Date has less than 6-months dating. Please verify Expiration Date!”, “Expiration Date Verification Required”) = vbOK -- Message posted via AccessMonster.com http://www.accessmonster.com/Uwe/Forums.aspx/databases-ms-access/2007...

colorified (html) lisp code output (pprinter)
(defparameter *example-code* (copy-tree '(defun get-llk (llst rt-lst &aux (result-list (make-list (1+ (length rt-lst)))) (tail result-list)) (apply #'values (mapl (lambda (lst) (rplaca lst (nreverse (car lst)))) (dolist (i llst result-list) (if (memq i rt-lst) (setq tail (nthcdr (1+ (position i rt-lst :test #'eq)) result-list)) (push i (car tail))))))))) ;; ------- I have this: ;; (html-write *example-code*) ;; <pre> (<code style="color: red">DEFUN</code> GET-LLK ...

code matlab (local discriminant)
salut, je suis �tudiant de magister en �lectronique, et je travaille avec les paquets d'ondelettees comme m�thode d'analyse, et plus exactement avec l'algorithme dit "local discriminant basis" j'aimerai bien avoir un code de cet algorithme impl�ment� sous matlab, pour ne pas perdre enorm�ment de temps dans des choses d�ja faites Merci Mohammed BACHIRI ...

permission for code
This is for your kindness to help me in doing my project on image fusion...could any one please help me to find the matlab code for the topic "Image fusion of pan and ms image using NSCT".Waiting for your posetive reply On Tue, 19 Feb 2013 19:04:07 +0000, Stegin Joy wrote: > This is for your kindness to help me in doing my project on image > fusion...could any one please help me to find the matlab code for the > topic "Image fusion of pan and ms image using NSCT".Waiting for your > posetive reply aw, damn... Google is down, again?!? ...

[ace-users] Regarding errors while compiling ACE code
Hi! We are trying to compile opendiameter source code (opendiameter-1.0.7-g) using ACE framework (ACE-5.4). > ACE version 5.4, released Wed Jan 14 18:45:46 2004. And, while we try to compile the code, we found that certain number of header files were missing in Red Hat Linux 9 machine. Also, we got some errors in ACE header files. # uname -a Linux kajol 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686 i686 i386 GNU/Linux Could you please let me know if I have missed any patches? Regards, Murali Errors:- (I have attached the error log along with...

[ANN] pyparsing 2.0.1 released
In my releasing of Pyparsing 1.5.7/2.0.0 last November, I started to split = supported Python versions: 2.x to the Pyparsing 1.5.x track, and 3.x to the= Pyparsing 2.x track. Unfortunately, this caused a fair bit of pain for man= y current users of Python 2.6 and 2.7 (especially those using libs dependen= t on pyparsing), as the default installed pyparsing version using easy_inst= all or pip would be the incompatible-to-them pyparsing 2.0.0. I hope I have rectified (or at least improved) this situation with the late= st release of pyparsing 2.0.1. Version 2.0.1 takes advantage of the...

DB2 8.1.5 SQL1224N Error
Hi, We have a custom application used by a customer on DB2 8.1.5 AIX 5.1, we have tested it with 8.1.0 AIX 5.1 and everything works fine. But with 8.1.5 we get the above error. The other applications connecting to other instances of the database works fine. lsattr -E -l sys0 | grep maxuproc gave the output maxuproc 4096 ps -ef | grep <instance Name> | wc -l returned 665 Also have checked on the extended shared memory to be used, in fact the customer is using the TCP/IP, and this works, if the application connects from a Windows environment. It seems to be a pro...

hack this code :)
hi all, would you please help me find any security flaw in this code (if any)? thank you so much http://paste.uni.cc/9829 bye -- NoWhereMan -- NoWhereBlog: www.nowhereland.it -- deviantArt: http://nowhereland.deviantart.com -- Giochi a BiteFight? http://bitefight.nowhereland.it/ -- Vagisil migliora la tua vita intima: www.vagisil.com/teencenter.shtml "NoWhereMan" <nowhereman@PLEASEDONTSPAMMEdespammed.com> wrote in message news:1azsskychkur$.9m67wioajmka.dlg@40tude.net... > hi all, > > would you please help me find any security flaw in this code (if any)? > tha...

need some insights (dynamic code genration on DSP's)
Hi compilers group. I'm working on a small dynamic code generation project and I need some help or direction where to look at (essencial books ect). Some background first: My goal is to write a dynamic code generator for multi-media applications running on a DSP (TI C64Plus). Just simple rendering loops - two times nested will be the most complex thing I'll ever have to deal with. I did something similar before on a MIPS 64 style CPU (NEC Vr5500 CPU), and I have decades of experience outperforming compilers with hand written assebly code. Just glueing pieces of code together on the...

Please critique my discriminant code?
I am trying to write a linear discriminant MATLAB routine, but am stuck at the following. Is this correct? Where is the cut-off between classes? thanks for any assistance you may provide, Will % LDA - MATLAB subroutine to perform linear discriminant analysis % by Will Dwinnell % % Last modified: Oct-14-2004 % % Use: % W = LDA(Input,Target,Method) % % W = discovered linear coefficients (first coeff. is the constant) % Input = predictor data (variables in columns, observations in rows) % Target = target variable (class values 0 and 1) % Method = discriminant method to use % ...

Hiding Matlab Code
Hello. I wrote few functions in Matlab which I want to share with some people. Yet all I want to share is the functionality of those functions - I want to hide the algorithm inside it. Lets say I wrote a function to Denoise an image: DenoisedImage = ImageDenoise(Image, NoiseReductionLevel) Matlab Code... end I want to have others the option to run the function "ImageDenoise" yet the code should be hidden (They won't be able to figure out how it works). How can I do that? Any ideas would be great. help pcode Also, search the newsgroup for discussion of ju...

How to prevent HTML code such as &lt; being rewritten as <
Folks, I'm struggling to put the question together, but I have this problem. I have written an HTML form that I can use for data entry. This uses PHP to write a SQL UPDATE command that gets written to my MySQL database. I can later view this data back in the form. One thing I've noticed happening is if I enter code such as &lt; it gets rewritten as < (ie the less-than sign). Now I don't want this to happen, but something somewhere is converting this. This is annoying because it messes up my HTML code. The HTML form calls itself (ie $_SERVER['PHP_SELF']), and then ...

Trying to understand this code
Here is the code I found: <script language="JavaScript"> <!-- if (parent.frames.length > 0) { parent.location.href = location.href; } --> </script> What it looks like I'm seeing is a function that will automatically break the page out of any frameset it finds itself in. Am I right? Chad Lupkes chadlupkes@yahoo.com chadlupkes@yahoo.com (Chad Lupkes) writes: > Here is the code I found: > > <script language="JavaScript"> It's <script type="text/javascript"> In HTML 4, the type attrbute is required. > &l...

read file with WINDOWS API
Hi, can i help me with the api in clarion.. the api to open file in inside the global map MODULE('Windows API') _lopen(*CSTRING,SIGNED),SIGNED,PASCAL,RAW END in procedure routine f# = _lopen(fichero,2) but the file is not open.. return error -1 can i help me, please What is in fichero? is it possible this file is already open? -- -- Leonid Chudakov chudakov@klarisoft.com Cool tools and Clarion examples at http://www.klarisoft.com "Franky" <franmr@jazzfree.com> wrote in message news:e51f0k$gv5$1@nsnmrro2-gest.nuria.telefonica-data.net... > Hi, > &g...

Print Tools for Outlook 1.8
Print Tools for Outlook is a Microsoft Outlook add-in. It will help you automatically print incoming and outgoing messages with attachments (as well as messages and attachments separately) without even opening them. The plug-in automatically unpacks and prints packed ZIP and RAR attachments, and supports manual and automatic working modes. Program settings necessary for the automatic working mode are intuitively clear and few in number. Messages printed with Print Tools look exactly the same as those printed by the standard means of Microsoft Outlook. But the plug-in makes up for some ...

(????) [1/1]
here u go m8 -- Posted via NewsDemon.com - Premium Uncensored Newsgroup Service ------->>>>>>http://www.NewsDemon.com<<<<<<------ Unlimited Access, Anonymous Accounts, Uncensored Broadband Access ...

Installating applications on a Mac
What is the typical file extension for a file that would be run on a Mac to install a program? For example, in Windows XP an install program generally has an EXE extension, as it is an executable. For example, I've used STUFFIT to decompress/decode a Mac program which is supposed to be an application package, but I can't find any obvious install program, which I should open (double-click on) to install the application. In article <1164681137.676748.247800@80g2000cwy.googlegroups.com>, "Dave" <davidjchurchill@gmail.com> wrote: > What is the typical file ex...

what is the java code
If You were hired by a gasoline firm to create a program that will tell whether which route is faster and which route is more likely to be fuel efficient separately. A test car was provided for you to model your software. This test car holds a full tank of 40 Liters and burns fuel at a rate of 7 Liters per kilometer. Your software should be able to ask two alternate routes from the user and its corresponding distances in kilometers. Assume that the allowed speed limit is at 40 KPH. After entering the required values your program should tell the user which route is the fastest and which route i...

Contractors fired for using GPL code
"I *DO* know of 2 companies where this happened. Contractors from Russia and India were hired to do a job, and it turned out that they used GPL'd code. In one case, management fired them and had a different contractor write new code, in the other management chose to continue to use it after they were alerted to it, because they argued it was too expensive to rewrite." "I can't give you the names of the companies though, as I was under contract and non-disclosure, so take it with however many boulders of salt you like." Erik Funkenbusch Oct 26 2005 I just *knew* ...

[ANN] soap4r-1.5.6
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, 'SOAP4R' is an implementation of SOAP 1.1 (W3C Note). http://www.w3.org/TR/SOAP/ RAA: http://raa.ruby-lang.org/project/soap4r Release Note: http://dev.ctor.org/doc/soap4r/RELEASE_en.html soap4r/1.5.6 is out. It is 1 and 3/4 years from 1.5.5. Sorry for the late release. It contains many feature improvements and bug fixes. changes: http://dev.ctor.org/doc/soap4r/RELEASE_en.html#changes download: http://dev.ctor.org/download/soap4r-1.5.6.tar.gz http://dev.ctor.org/download/soap4r-1.5.6.zip sha1sum: f8513624a008c9bf978...

seeking opinions/reviews of M-AUDIO 'FireWire Audiophile'
I'm looking for a device that will let me connect a powerbook to the coax input of a digital-analog converter. My primary use for this right now will be to play 16-bit 44.1KHz aiff files. I don't need support for higher resolution digital data right now, but it might be useful to have it for future use. I might occasionally want analog output and the ability to record from 2-channel line-level analog inputs, but these are both secondary. One item I'm looking at is mentioned in the Subject line. If anyone has opinions about the M-Audio, please post. There are features here I do...

7bit coding ? NO 8bit coding
If you told about reading outside file inside d3 BASIC/PRogram Create doc file with 1!! symbol of 'ef' Please take follow PICK/BASIC code and execute it ..... FWay = "nt_bin:E:/your_file" OPEN FWay TO FHandle ELSE STOP MAX_BLOCK = 256 * CHAR Val[MAX_BLOCK] READ Val FROM FHandle,"your_file" THEN FOR I=1 TO LEN(Val) CRT SEQ(Val)"R#3":" ": NEXT I CRT END * END I get 52 52 52 52 52 52 52 52 52 May be I made something wrong or 'ef' is really transformed in sev...

Multiple Domains; 1 Server; 1 PHP Install; Only One Domain Has A Working PHP; WHY??????
I am going crazy. This has been a problem now for over a year and I have yet to figure out what is causing it. I have a single server that is running multiple domains. For this example I will list four domains all of which have the phpinfo.php file in their root directories. However, only one of them has working PHP. What am I doing wrong? http://www.lyricvault.com/phpinfo.php http://www.paynephotos.com/phpinfo.php http://www.brentdavidpayne.com/phpinfo.php http://www.brentdavidenterprises.com/phpinfo.php http://www.lyricvault.com http://www.paynephotos.com http://www.brentdavidpayne.co...

Make easy money!! NO SCAM!! Please Read!
NEED QUICK EASY CASH??? Turn $6.00 into $60,000...read this to find out how!!! READING THIS COULD CHANGE YOUR LIFE!!! I found this on a bulletin board like this one and decided to try it. A little while back, I was browsing through a newsgroup, just like you are now, and came across an article similar to this that said you could make thousands of dollars within weeks with only an initial investment of $6.00! So I thought, "Yeah right, this must be a scam", but like most of us, I was curious, so I kept reading. Anyway, it said that you need to send $1.00 to each of the 6 names and add...

C-style bracket-matching for lisp code?
This may seem blasphemous to old-school lisp hackers, but I would like to set up my emacs to auto-indent my lisp brackets like C, for example (defmethod cat meow () __(let ((xs ys)) ___(each ((x xs)) _____;comments should line up with the line below them _____(print x) ___) __) ) .... ie so the closing brackets line up with their opening partners. (Coming to lisp from C and Java this makes a lot more sense to me than the emacs default style) I'm not yet an expert on writing emacs modes (though my lisp is ok) -- does anyone have something I could put in my .emacs file to do this; or fail...