We have a simple query and insert using C code linking to mysql db. The issue now on itself the script works fine. But when we put to run as a cron job the select query gives empty results and when we run back on the db there is results. It really puzzle as to what extra should be done for it to a cron job?

Edited 3 Years Ago by deceptikon: Probably more appropriate for linux/unix forum


It is hard to tell what is wrong without seeing the cron entry you ae using or the code. However the first things that come to mind are that cron jobs are not run with the same environment variables as a normal user. You have to call the program using the absolute path of the file you are trying to run (i.e. /home/me/myscript ) and if there are any variables set that are specific to you login they need to be set when you script runs. You could try checking the cron logs and mysql logs to see if they show any errors.

Right, I was thinking 'permissions'. But rch1231 is correct. It's more likely the environment variables.

If you could post the cron entry and any important errors in the logs, that would be a big help.

dear all, below is my c codes.

MYSQL *localConn;
    MYSQL_RES *localRes1;
    MYSQL_ROW localRow1;
    timer_t tid = 0;
    pthread_t thread;
    struct itimerspec it;
    char *server = "localhost";
    char *user = "user1";
      char *password = "*******"; /* set me first */
      char *database = "packets";
      localConn = mysql_init(NULL);
      if (!mysql_real_connect(localConn, server,
             user, password, database, 0, NULL, 0)) {
          fprintf(stderr, "%s\n", mysql_error(localConn));

        struct timeval tv;
            char timeBuf[10],secondBuf1[100],queryBuf1[500],queryBuf2[500];
            char buff1[20] = {0};
            char buff2[20] = {0};
            gettimeofday (&tv, NULL);
            strftime(buff1, 20, "%Y-%m-%d %H:%M:00", localtime(&tv.tv_sec));
            strftime(buff2, 20, "%Y-%m-%d %H:%M:59", localtime(&tv.tv_sec));
            printf("\nTime from %s", buff1);
            printf("\nTime to %s", buff2);

          sprintf(queryBuf1,"SELECT field1, field2,field3, sum(totalCount) FROM tblR1 WHERE timeStamp between '%s' And '%s' ",buff1,buff2);
                printf("\nQuery receive %s",queryBuf1);

                if(mysql_query(localConn, queryBuf1))
                    //fprintf(stderr, "%s\n", mysql_error(localConn));
                    printf("Error in first query of select %s\n",mysql_error(localConn));

                localRes1 = mysql_store_result(localConn);
                int num_fields = mysql_num_fields(localRes1);

                printf("\nNumf of fields : %d",num_fields);
                printf("\nNof of row : %lu",mysql_num_rows(localRes1));

                //output table name
                //printf("Mysql Tables in mysql database: \n");
                while((localRow1 = mysql_fetch_row(localRes1)) !=NULL)
                  int totalBits = atoi(localRow1[3]);

                  printf("totalBits %d\n", totalBits);
                  printf("RECEIVE %s,%s\n", localRow1[0], localRow1[1]);
                    sprintf(queryBuf1,"INSERT INTO tblTR1 (timeStamp,field1, field2, field3, field4)VALUES ('%s','%s','%s','%s',%s)",buff1, localRow1[0],localRow1[1],localRow1[2],localRow1[3]);
                    printf("Query 1 before executing %s\n",queryBuf1);
                    if (mysql_real_query(localConn,queryBuf1,strlen(queryBuf1))) {
                   printf("Error in first query of select %s\n",mysql_error(localConn));
                   fprintf(stderr, "%s\n", mysql_error(localConn));
                    //printf("Query 1 after executing %s\n",queryBuf1);*/



Cron settings and the receive1.c is the output file not the source file. It is already compiled.

/1 * * * * /home/test1/userland/examples/receive1.c  2>&1 >> /var/log/myjob.log

My env variables are as below.

Output from env.

SSH_CLIENT= 4383 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
module=() {  eval `/usr/bin/modulecmd bash $*`

Then I run a crontab * * * * * env > /tmp/env.out and below is the output.

LOGNAME=root _=/usr/bin/env a

So what is the possible problem because if you see the path are showing difference.


I don't know enough about C programming to be able to tell you what to do there but I suggest that you try putting your variables into a shell script file with the c program called at the very end and call that program instead of the c file:

export PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
export TERM=xterm

Edited 3 Years Ago by rch1231

Dear rch1231, I tried it via shell script still the same issue the C script runs and when comes to the results part it show empty. Then when I just run ./firsrule.sh it works perfectly fine and able to generate results. I do know why when it runs via cron is where the problem.


Ok so how does you program normally return the results? If it normally displays to the screen then you need to redirect the output to a file either from within your C code or by redirecting STDOUT in the shell script:

/home/test1/userland/examples/receive1.c > /home/test1/userland/examples/output

I code alot with perl and when I am trying to save the results from a query or making changes to a file, I open a file for output and then print the results to the file a line at a time. I know it is not C (sorry I don't know C) however here is a piece of perl code to read a multiline record and export it as a one line csv.

`my $delim = "',";

### converts a multi-line record into a single line CSV file.

my $file = "$ARGV[0]";
open OUTGOING, ">", "$file" . ".csv";
my $lineone = 0;
open(FILE,"<$file.txt") or die "ERROR $file: $!\n";
while(<FILE>) {
    my $stuff = $_;
    my $firstslash = index( $stuff , "=");
    my $fieldname = substr $stuff , 4 , $firstslash  ;
    my $fielddata = substr $stuff , $firstslash +2  , 1000 ;
if ($lineone == 1) {
    if ( /EBOM_Item/  ) {
        print OUTGOING "\n";
    else { print OUTGOING "'$fielddata$delim" ;
    $lineone = 1;

Normally I just printf and it gets written to the log /var/log/myjob.log file when I run via cron. The funny part when the select is run via cron it returns empty results and when I run the shell script it works perfectly fine with the relevant results generated via the select statement.

This is not a C code problem. It is most likely a misconfigured cronjob problem. Show the crontab please, as well as user ID for interactive use.

Here is the crontab setting /1 * * * * /home/test1/userland/examples/receive1.c 2>&1 >> /var/log/myjob.log dont worry about the receive1.c name is a compiled version of the source codes. The user is root to avoid any permission problems. What could be wrong ya?


Well the only other thing I can think of is that cron runs without a terminal type being set. If your script needs a terminal type set to format the output then add the line:

export TERM=xterm

To the shell script you call the C code from.

The export is already from the time I build the shell script as per your suggestion.

export PATH=/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
export TERM=xterm
This article has been dead for over six months. Start a new discussion instead.