code review: read in ps(1) result

  • Permalink
  • submit to reddit
  • Email
  • Follow


/*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
Reply lovecreatesbeauty (722) 7/16/2010 12:44:31 PM

See related articles to this posting


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
Reply 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
Reply 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
Reply 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
Reply 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
Reply nobody (5158) 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
Reply 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
Reply lawrence 7/27/2010 3:38:54 PM
comp.lang.c 29483 articles. 32 followers. Post

7 Replies
220 Views

Similar Articles

[PageSpeed] 41


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

ANNC: Code Co-op v4.1 simplifies code review and merges
Seattle-based Reliable Software announces the release of Code Co-op version 4.1. Code Co-op is the affordable peer-to-peer version control system supporting distributed development through Email, LAN, and VPN. Code Co-op v4.1 features the inclusion of Beyond Compare Differ 2.1, a �lite' version of Beyond Compare� 2.1 by Scooter Software, Inc. This �lite' version was created especially for Code Co-op. Users can choose between the built-in differ and the Beyond Compare Differ. Version 4.1 also includes integration with the Beyond Compare 2.1 and Borland Delphi 8. Code Co-op 4....

zlib/deflate
Hallo, when calling the deflate funktion one time I get the result code 0 (Z_OK) and with another string the result code 1 (Z_STREAM_END). What does ist mean ? When get I the code 0 and when the code 1 ? I get no error when I ignore the 1 ! Is the code 1 also 0, or what must I do ? Thank you for response Regards Wolfgang Schwarz 34582 Borken / Germany Wolfgang Schwarz wrote: > Hallo, > > when calling the deflate funktion one time I get the result code 0 (Z_OK) > and with another string the result code 1 (Z_STREAM_END). > What does ist mean ? When get I the code 0 and w...

PITR Phase 1 Code Review
Please could the committers review my code with a view to committing it onto the main dev branch? There are additional cosmetic changes likely to be required, such as removing some dead comments and streamlining log output. Let me know whether these should occur before or after first commit. I'll be around daily to answer queries and fix reported bugs. Thanks, Best Regards, Simon Riggs ---------------------------(end of broadcast)--------------------------- TIP 8: explain analyze is your friend ...

Sending code to *scheme* buffer and reading the result
Hello, Emacs' scheme-mode has code for sending a sexp to the *scheme* buffer. But, I need to code to send an sexp, and return the result, as an sexp. I'm sure somebody has done this before and I'd like to borrow that code if possible. I know about Jao's awesome Geiser mode and I could factor out the relevant parts. Just wondering about other possibilities. Thanks! Ed Eduardo Cavazos <wayo.cavazos@gmail.com> writes: > Emacs' scheme-mode has code for sending a sexp to the *scheme* buffer. > But, I need to code to send an sexp, and return the result, as an >...

Help! IBM PS/1 error codes 161 and 163
Help! At boot-up I get error codes 161 and 163 underneath (re-booting doesn't solve). DOS Shell re-settings are lost on switch-off, time and date reset to midnight 1980 etc too. Copying to floppy drive is erratic. Any ideas? A battery somewhere? The Manual solutions don't work (error code 161 - rebooting doesn't solve it. 163 - time and date can be set but are simply lost again at switch off). ...

[ace-users] Error code 1 returned in ACE_Asynch_Read_Stream::Result
This is a multi-part message in MIME format. ------_=_NextPart_001_01C54F2B.3A1E7850 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Platform : Win32 Version : 5.3 =20 We're using the Proactor pattern for async communications between a client and a server component. I have an ACE_Svc_Handler derived class receiving result.bytes_transferred() =3D=3D 0 and result.error =3D=3D 1 = on return from handle_read_stream override. This happens occasionally, every 5-15 minutes or so (the app re-establishes socket connection ...

[ANN] PySourceColor 1.9.6 much new code please review
Hello all , I have just finished PySourceColor.py ver 1.9.6. I am near the end of this tool, and would appreciate a little bit of review. Please help me find the pesky little bugs that have escaped me. I had much difficulty getting linenumbers to work properly. If you see a simpler way to do linenumbers, by all means, please share. Website: http://bellsouthpwp.net/m/e/mefjr75/ Here is the module docstring to start you off: """ ############################################################################# # PySourceColor.py #######################################################...

What is code review? (Java code review)
Hi,My boss just told me a concept I didn't know. (I am middle level Java programmer.) -- "code review".According to what I heard, "code review" is somebody reads the thousands lines of code written by other person and try to find if there are some errors (logic errors, I guess, since the code at least can be compiled and run).I feel this is crazy!!! Since the reviewer has to "read" the original code author's mind and make sure the code does what the author wants and no hidden surprises! How this could be possible?! This would be extremely time consuming an...

PS 1.1 ?
I have a game that says I need PS 1.1 installed. Does anyone know what this is? How can I get it. On Sun, 7 Sep 2008 11:27:53 -0700 (PDT), Rich <richmarin@earthlink.net> wrote: > > >I have a game that says I need PS 1.1 installed. Does anyone know what >this is? How can I get it. Do you know what Google is? Its Pixel Shader 1.1 and if your card doesn't give you that, or your integrated chip, then you definitely need a new comp. You don't install it either, its hardware. Out of interest, what game is it? Best Orggl Previously Orggl Arh...

Strange math result... 1-1= -1 ???
See something weird on this result? 632.35 - 632.35 = -1.13686837722E-013 If anyone has seen something similar, please let me know! this a part of the code: $total_due = abs( $order_total ) - abs( $total_paid ); echo( $order_total . " - " . $total_paid . " = " . $total_due ); I've added the abs() in order to be sure that I'm dealing with numbers, I've also used is_numeric() and confirmed it. The echo() is showing the result I pasted up there. any ideas?? I have never seen that before and no clue as how to fix it. But for a work around, use... $output ...

`timescale 1 ps / 1 ps(verilog command equivalent in VHDL.
hi all, I want know how to write `timescale 1 ps / 1 ps equivalent in VHDL. sheri a �crit: > hi all, > I want know how to write `timescale 1 ps / 1 ps equivalent in VHDL. > You can't. -- Vince On Feb 27, 12:46=A0pm, Vince <debo...@free.fr> wrote: > sheri a =E9crit: > > > hi all, > > I want know how to write `timescale 1 ps / 1 ps equivalent in VHDL. > > You can't. > > -- > Vince Thanks Vince. But I want to know Is there any other way to do time_unit and resolution settings in VHDL. sheri a �crit: > On Feb 27, 12:46 pm, Vince &...

RxParse 1.1
This is one of the best little XML SAX parser's I have ever used. Totally Perl, doesen't use any dll wrappers. ################################################################# # AUTHOR: robic0, copyright (c) 2006-2007 # Reproduction of contents, or distribution in a comercial # product, is strictly prohibited without prior written # permission from the author. ################################################################# # XML/Xhtml/Html - RXParse parse/edit/filter module # ------------------------------------------------------ # Compliant w3c XML: 1.1 # Resources: # Extensibl...

Poll : do you do peer reviews / code reviews / design reviews
I recently read on Phil Koopman's blog http://betterembsw.blogspot.com/ that peer reviews should be finding approx half of errors and testing find the other half. Where I work we do very few peer reviews of software. We have mostly experienced people and my boss thinks code reviews cost time with not much benefit. I'm wondering how many embedded software places consistently do code reviews of software and how many do little or none? Does the level of review vary according to the experience/ ability of the programmer? Does the design and logic/ correctness of the code get reviewed ...

Review of eCS 1.1
http://www.os2ezine.com/20030416/page_2.html "The bottom line for current eCS users is that if this was an easy upgrade, with all the cool new goodies, updated codebase, slick installer and the $59 upgrade price, I'd definitely say go for it. However if you have a working eCS 1.0 system, the uncertainty of the upgrade path makes the decision a little more difficult. In the end, I've decided I'm going to buy the upgrade for my eCS system, but I'm not looking forward to it as much as I would be if installation was a matter of just putting in the CD and waiting. "...

Code Review
A geek and linux hacker from china wrote this piece of code in his / her unfinished book "the art of C programming". Under which version of C standard will it be correct? The author may think it is correct under at least some older C versions. This person submitted patches to linux kernel. Linus ever gave comment on mailing list like this to those patch code: You code is shit. Is this code really shit? /* check endianess, http://wangcong.org/down/chapter2-beta.pdf */ #include <stdio.h> #include <stdlib.h> int main(X) {exit(0 > puts((*(char *)&X == (char)X)?&quo...

Aperture 1.1 Reviewed!
Aperture 1.1 Reviewed! Ars Technica's review of Apple's Aperture 1.1. For more details: http://ttcom.blogspot.com/2006/05/aperture-11-reviewed.html ---------------------------------------------------------------------------------------- Organize your photos by picasa: http://tt.picasa.googlepages.com/home ttppmm@gmail.com wrote (in article <1147296337.859432.183740@y43g2000cwc.googlegroups.com>): > Aperture 1.1 Reviewed! > > Ars Technica's review of Apple's Aperture 1.1. > > For more details: > <spam snipped> What a pathetically lame way t...

Aperture 1.1 Reviewed!
Aperture 1.1 Reviewed! Ars Technica's review of Apple's Aperture 1.1. For more details: http://ttcom.blogspot.com/2006/05/aperture-11-reviewed.html ---------------------------------------------------------------------------------------- Organize your photos by picasa: http://tt.picasa.googlepages.com/home I didnt know they made Aperture 1.1 for the Apple II, but maybe someone knows something I dont. bill.martens@gmail.com wrote: > I didnt know they made Aperture 1.1 for the Apple II, but maybe someone > knows something I dont. > jackass trying to bump...

Aperture 1.1 Reviewed!
Aperture 1.1 Reviewed! Ars Technica's review of Apple's Aperture 1.1. For more details: http://ttcom.blogspot.com/2006/05/aperture-11-reviewed.html ---------------------------------------------------------------------------------------- Organize your photos by picasa: http://tt.picasa.googlepages.com/home -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 In article <1147296356.392272.75970@u72g2000cwu.googlegroups.com>, <ttppmm@gmail.com> wrote: >Aperture 1.1 Reviewed! ....and this has what to do with the Apple II, exactly? Idiot. _/_ / v \ ...

Auction: 2 PC mice mouse 1 serial 1 PS/2 PS / 2 IBM save them! ;)
Included primarily for humor purposes. To keep it somewhat on topic, one is an IBM "soap bar" mouse. I think it's pretty funny. Quoting directly from the listing: "What you're bidding on: 2 PC Mice, cheap. All are tested and working. Save these from the dumpster." http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=140076586464 Ends Jan-25-07 Starting bid $1.25, shipping $4.50. Ships to US and Canada from Fort Plain, NY. No affiliation. William ...

Oniguruma: Different result in ruby 1.9.1 and 1.8.7
Hi, I have the following regular expression created in ruby 1.9.1: /(?:(?:\$(?'name1'[\w\s\']+)(?:(?'name2'(?:created|developed)[\w\s]+)(?name3'(?:in|at)[\w\s]+)))|(?:\$(?'name1'[\w\s\']+)(?'name2'(:?created|developed)[\w\s]+))|(?:\$(?'name1'[\w\s\']+)(?'name3'(?:in|at)[\w\s]+)))(?:\.(?'name4'[\w\s]+))?/.match(str) To use Oniguruma i have installed the following gem: http://github.com/geoffgarside/oniguruma/tree/master (also tried with this solution: http://www.goodbyehelicopter.com/2008/02/20/install-oniguruma-on-os-x...

reading netCDF 4.1.1 using IDL version 6.1
Hello, Does anyone know how to fix the issue in reading netCDF 4.1.1 with IDL version 6.1. When I open the file with 'ncdf_open' function, I get an error saying 'NC_ERROR=-51'. Thanks, Mahesh mkmvarma@gmail.com writes: > Does anyone know how to fix the issue in reading netCDF 4.1.1 with IDL version 6.1. When I open the file with 'ncdf_open' function, I get an error saying 'NC_ERROR=-51'. You will need to download the Clairvoyant Module. I'm not sure if it is still available on the Exelis web site or not. You could ask them. Cheers, Da...

ps/2 to ps/1 adapter
Hi First of all, sorry for my not-so-good english I have this very awesome dvorak-keyboard, and it types very well, but the problem I have is that the dvorak is rather old and has a ps/1 plug. the computer I work on only has a ps/2 So I went to the store, to buy a ps/1 to ps/2 adapter, and almost every store in the neigbourhood says they don't sell it anymore. My question is: does anyone know the scheme of such adapter, so I can make it myself? (plugs aren't the problem, but I'm wondering which pin should be connected to which pin) Thanks in advance Theo Vermeulen -- The...

Where is source code for Struts 1.1?
Does anyone know where I can obtain the source code for Struts 1.1? Now that Struts is an Apache project (not Jakarta) I can't find the source (or bianry) distributions for previous versions. Andrew Hammer wrote: > Does anyone know where I can obtain the source code for Struts 1.1? > Now that Struts is an Apache project (not Jakarta) I can't find the > source (or bianry) distributions for previous versions. Do you know how to use a browser?! Seriously, on the off chance that it had somehow disappeared (highly unlikely!), I went to jakarta.apache.org. A grand total of 5 (co...

Reading matrix elements 1 by 1
Hi all, I need some help here. I have a very big matrix of an image, that I am trying to convert to binary. So whenever the intensity of each pixel in the matrix is above the specified threshold I want to convert it to to 1. Would that involve a loop to go through all the items in my matrix or does matlab include a function which can do the lookup of the values for me ? I know I can use im2bw but my specification requires that I do not. Thanks andrew nicholson wrote: .... > I have a very big matrix of an image, that I am trying to convert to > binary. So whenever the intensity of ea...