Mysterious Redis C core dump - c

I am currently running a C program calling a Redis Server instance. After the 1020th iteration, it always bombs with:
Redis Connect 1021 Error: System error Segmentation fault (core
dumped)
Ugh. Something tells me one of the pointers decided to go wild. Can anyone help here? I am using the current version of Ubuntu Linux
//codingsteps.com/installing-using-hiredis-c-client-library-for-redis/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "hiredis.h"
void redisTest(void) {
redisReply *reply;
long int i;
// Start measuring time
clock_t start = clock();
// For local connections:
//redisContext *c = redisConnect("127.0.0.1", 6379);
redisContext *c = redisConnect("localhost", 6379);
// For connections to a remote Redis server:
//redisContext *c = redisConnect
// ("ec2-**-**-***-**.compute-1.amazonaws.com", 6379);
if (c->err) {
printf("Error: %s\n", c->errstr);
}else{
printf("Connection Made! \n");
}
// Get all keys for testing
//reply = redisCommand(c, "keys %s", "*");
reply = redisCommand(c, "lrange EUR 0 10", "*");
if ( reply->type == REDIS_REPLY_ERROR )
printf( "Error: %s\n", reply->str );
else if ( reply->type != REDIS_REPLY_ARRAY )
printf( "Unexpected type: %d\n", reply->type );
else {
for ( i=0; i<reply->elements; ++i ){
printf( "Result:%lu: %s\n", i,
reply->element[i]->str );
}
}
printf( "Total Number of Results: %lu\n", i );
// Output Elapsed time
printf ( "%f Seconds\n", ( (double)clock() - start ) /
CLOCKS_PER_SEC );
redisFree(c);
freeReplyObject(reply);
}
int main(void) {
int i = 0;
for(;;) {
printf("\n\nRedis Connect %d\n",i++);
redisTest();
}
}
Update: I added redisFree() as suggested by others (thanks for that). This still core dumps but after 28233 iterations.

Related

What is causing the thread to wait?

This code isn't finished yet so right know it should just print the lines out. but i cant figure out whats locking the first P( direc_sem );
#include <sys/types.h>
#include <sys/ipc.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include "sem_ops.h"
#include <semaphore.h>
#define MAXCARS 5
#define MAXWAIT 20
#define CROSSINGTIME 4
int G_direction = 0, direc_sem, car_E;
int carNum;
int retVal=0, lower = 0, upper = 1;
int car_rid[MAXCARS];
pthread_t threads[MAXCARS];
const char* printRandoms()
{
int num = (rand() % (upper - lower + 1)) + lower;
if (num == 0){
//left headed west
return "west";
}else return "east";
//return num;
}
void *car(void *arg) {
int carNum = (int)(intptr_t)arg; //what car is it
const char* direction = printRandoms(); //random direction
printf(" car no %d is idling, planning to go %s \n",carNum, direction);// test print
sleep( rand() % MAXWAIT ); // wait a random amounnt of time
//P( reader_sem );
//readers++;
//if( readers == 1 )
// P( counter_sem );
//V( reader_sem );
P( direc_sem );
if (G_direction >=0){
G_direction++;//->> move on to bridge
if (G_direction == 1){//if first car on bridge lock other traffic
P(car_E);
}else {
printf("stuck");
}
}
V(direc_sem);
printf("car no %d goes on the bridge heading %s \n", carNum,direction);
sleep(CROSSINGTIME);
printf("car no %d goes off the bridge heading %s \n", carNum, direction);
P(direc_sem);
G_direction--;//->> move off the bridge
if (G_direction == 0){//if last car on bridge unlock other traffic
V(car_E);
}
V(direc_sem);
//bridge no longer empty
// printf("W car# %d => %d\n", carNum, G_direction);//print test
// }// wait till westbound car is free
}
void Truck(){
}
int main( void ){
direc_sem = semtran( IPC_PRIVATE );
car_E = semtran( IPC_PRIVATE );
for (int i = 0; i < MAXCARS; i++){
retVal = pthread_create(&threads[i], NULL,car ,(void *)(intptr_t)i);
if(retVal!=0){
printf("pthread_create failed in %d_th pass\n",i);
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < MAXCARS; i++){
retVal = pthread_join(threads[i], NULL);
if(retVal!=0){
printf("pthread_join failed in %d_th pass\n",i);
exit(EXIT_FAILURE);
}
}
//sem_destroy(&carLock);
return 0;
}
compiled with wrong file definitely been at this too long thank you

Music Player program freeze on Xbox

I am making a music player called XMusic, which you might know from another problem I have posted here. If you don't, I am making it for PC and Xbox (using nxdk), and it uses the SDL_mixer library. I have the problem where it doesn't open any file to play it, but that's a different problem. Since yesterday I am also encountering a problem where it just freezes after selecting a file (or even using a fixed one). Here is an example with both of the mentioned problems (from here and from my other question)
#include <stdio.h>
#include <SDL.h>
#include <SDL_mixer.h>
#if defined (NXDK)
#include <video.h>
#endif
static int audio_open = 0;
static Mix_Music *music = NULL;
char* fileToPlay = "D:\\Pause Test.wav";
static void PlayFile() {
int audio_rate = 48000; //48KHz saves Xbox CPU time
Uint16 audio_format = AUDIO_S16LSB;
int audio_channels = 2;
int audio_buffers = 4096;
int audio_volume = MIX_MAX_VOLUME;
int looping = 1;
if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) < 0) {
printf("Couldn't open audio: %s\n", SDL_GetError());
}
else {
Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
printf("Opened audio at %d Hz %d bit%s %s %d bytes audio buffer\n", audio_rate,
(audio_format&0xFF), (SDL_AUDIO_ISFLOAT(audio_format) ? " (float)" : ""),
(audio_channels > 2) ? "surround" : (audio_channels > 1) ? "stereo" : "mono",
audio_buffers);
}
audio_open = 1;
printf("Setting volume\n");
Mix_VolumeMusic(audio_volume);
printf("Opening %s\n", fileToPlay);
SDL_RWops *rw = SDL_RWFromFile(fileToPlay, "rb");
if (rw == NULL) {
printf("Couldn't open %s: %s\n",
fileToPlay, Mix_GetError());
}
printf("Loading %s\n", fileToPlay);
music = Mix_LoadMUS_RW(rw, SDL_TRUE);
if (music == NULL) {
printf("Couldn't load %s: %s\n",
fileToPlay, Mix_GetError());
}
printf("Loaded %s\n", fileToPlay);
Mix_FadeInMusic(music, looping, 2000);
}
int main() {
#if defined (NXDK)
XVideoSetMode(640, 480, 32, REFRESH_DEFAULT);
#endif
SDL_Init(SDL_INIT_AUDIO|SDL_INIT_JOYSTICK);
Mix_Init(MIX_INIT_OGG|MIX_INIT_MP3);
PlayFile();
SDL_Delay(6000);
}
Running GDB on XMusic's debug build running on XQEMU (a low level emulator) shows me that it is stuck on 3 functions from SDL_mixer. Mix_HaltChannel(), Mix_QuerySpec(), and Mix_AllocateChannels(). It is like it is looping over all these 3.
XMusic's full code: https://github.com/kosmas12/My-code-stuff/tree/nxdk/Music%20player%20(C)

Segmentation fault (core dumped) with pulseaudio lib on c

I'm new to Stackoverflow and c and pulseaudio. Thanks for all help.
I get a the Segmentation fault (core dumped) error in the mainloop of a custom pulseaudiolib code. It it takes 1 to 30s to apear.
I am trying to get the audio data of a custom sink
pacmd load-module module-null-sink sink_name=MySink
pacmd update-sink-proplist MySink device.description=MySink
pacmd load-module module-loopback sink=MySink
use its data and pip it back to the speaker.
I'm pretty new at C and pulseaudio so I used the doc and https://menno.io/posts/pulseaudio_monitoring/
This is my code:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pulse/simple.h>
#include <pulse/error.h>
#include <pulse/context.h>
#include <pulse/def.h>
#include <pulse/format.h>
#include <pulse/introspect.h>
#include <pulse/stream.h>
#include <pulse/thread-mainloop.h>
const char * SINKNAME = "MySink";
const char * SPEAKNAME = "alsa_output.pci-0000_05_00.6.analog-stereo";
char found = 0;
const uint32_t RATE = 344;
pa_stream * gStream = NULL;
void stream_read_cb(pa_stream *stream, size_t length, void *index_incr){
printf("in read\n");
const void * samples[length];
size_t * leng;
(*leng) = length;
printf("length : %d, %d\n",length,(*leng));
int res = pa_stream_peek(stream, samples, leng);
pa_stream_drop(stream);
if(gStream != NULL){
int result = pa_stream_write( gStream, samples,length, NULL,0, PA_SEEK_RELATIVE);
}
printf("[");
if (res == 0){
for(int i = 0 ; i< length; i++){
printf("%d,",samples[i]);
}
}
printf("]\n");
}
void sink_info_cb(pa_context* context, const pa_sink_info *sink_info_p, int eol, void *userdata){
printf( "in sinkinfo\n");
const pa_sink_info* sink_info = sink_info_p;
if(found !=1){
printf( "index: %d\n", (*sink_info).index);
printf("help\n");
printf( "name: %s\n", (*sink_info).name);
printf( "description: %s\n", (*sink_info).description);
printf("searchName: %s\n",SINKNAME);
if (strcmp((*sink_info).name, SINKNAME) == 0){
found = 1;
// Found the sink we want to monitor for peak levels.
// Tell PA to call stream_read_cb with peak samples.
printf( "setting up peak recording using: %s\n ", (*sink_info).monitor_source_name);
pa_sample_spec *samplespec;
(*samplespec).channels = 1;
(*samplespec).format = PA_SAMPLE_U8;
(*samplespec).rate = RATE;
pa_stream * stream = pa_stream_new(context, "peak detect demo", samplespec, NULL);
pa_stream_set_read_callback(stream,
stream_read_cb,
( *sink_info).index);
pa_stream_connect_record(stream,
(*sink_info).monitor_source_name,
NULL,
PA_STREAM_PEAK_DETECT);
printf("settetd \n");
}/*
if((*sink_info).name[0] == 'a'){
//printf( "setting up peak recording using: %s\n ", (*sink_info).monitor_source_name);
//pa_sample_spec *samplespec;
// (*samplespec).channels = 1;
// (*samplespec).format = PA_SAMPLE_U8;
// (*samplespec).rate = RATE;
printf("set gStream");
//gStream = pa_stream_new(context, "peak detect demo", samplespec, NULL);
//printf("gSteam setted\n");
}*/
printf("out sink\n");
}
}
void context_notify_cb(pa_context *context, void *userdata){
printf("in context\n");
pa_context_state_t state = pa_context_get_state(context);
if( state == PA_CONTEXT_READY){
printf( "Pulseaudio connection ready...");
// Connected to Pulseaudio. Now request that sink_info_cb
// be called with information about the available sinks.
pa_operation * o = pa_context_get_sink_info_list(context, sink_info_cb, userdata);
pa_operation_unref(o);
}
else if( state == PA_CONTEXT_FAILED){
printf( "Connection failed");
}
else if( state == PA_CONTEXT_TERMINATED){
printf( "Connection terminated");
}
printf("out context\n");
}
void init(){
// Wrap callback methods in appropriate ctypefunc instances so
// that the Pulseaudio C API can call them
printf("in init\n");
pa_context_notify_cb_t _context_notify_cb;
//context_notify_cb(context_notify_cb void ** userdata);
pa_sink_info_cb_t(sink_info_cb);
pa_stream_request_cb_t(stream_read_cb);
// Create the mainloop thread and set our context_notify_cb
// method to be called when there's updates relating to the
// connection to Pulseaudio
pa_threaded_mainloop* _mainloop = pa_threaded_mainloop_new();
pa_mainloop_api* _mainloop_api = pa_threaded_mainloop_get_api(_mainloop);
pa_context *context = pa_context_new(_mainloop_api, "peak_demo");
pa_context_set_state_callback(context, context_notify_cb,NULL);
pa_context_connect(context, NULL, 0, NULL);
pa_threaded_mainloop_start(_mainloop);
printf("out intit\n");
}
int main(int argc, char*argv[]) {
init();
printf("Hello World\n");
while(1){
;
}
printf("end World\n");
return 0;
}
if I try to uncomment
/*
if((*sink_info).name[0] == 'a'){
//printf( "setting up peak recording using: %s\n ", (*sink_info).monitor_source_name);
//pa_sample_spec *samplespec;
// (*samplespec).channels = 1;
// (*samplespec).format = PA_SAMPLE_U8;
// (*samplespec).rate = RATE;
printf("set gStream");
//gStream = pa_stream_new(context, "peak detect demo", samplespec, NULL);
//printf("gSteam setted\n");
}
*/
the error shots like directly.
the output:
...
in read
length : 1, 1
[-1261830080,]
in read
length : 6, 6
[-1246625728,-1017902384,0,0,-1017902304,591610535,]
in read
length : 1, 1
[-1259864000,]
in read
length : 6, 6
[-1227227072,-1017902384,0,0,-1017902304,591610535,]
in read
length : 1, 1
[-1255800768,]
in read
length : 6, 6
[-1234960320,-1017902384,0,0,-1017902304,591610535,]
in read
length : 7, 7
[-1249247168,-939474438,-1017902512,-1017902384,0,0,-1017902304,]
in read
length : 7, 7
[-1242693568,-939474438,-1017902464,-1017902336,0,0,-1017902256,]
Segmentation fault (core dumped)
the uncomment output:
in init
in context
out context
out intit
Hello World
in context
out context
in context
out context
in context
Pulseaudio connection ready...out context
in sinkinfo
index: 0
help
name: alsa_output.pci-0000_05_00.6.analog-stereo
description: Family 17h (Models 10h-1fh) HD Audio Controller Analog Stereo
searchName: MySink
set gStreamout sink
in sinkinfo
index: 1
help
name: MySink
description: MySink
searchName: MySink
setting up peak recording using: MySink.monitor
settetd
Segmentation fault (core dumped)

ioprio_set is not showing gain in io performace of calling thread

This small experiment was to demonstrate the gain in I/O performance by increasing I/O priority of thread .
For this purpose ioprio_set system call was used.
To see this api in action you can explore code of ionice utility.
So, I have spawned some threads to copy some files of same size(where one thread copy one file to some output file)
and for one thread I have called ioprio_set.
ioprio_set(IOPRIO_WHO_PROCESS, 0, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_RT,0));
These parameter are such that it will escalate the priority of calling thread to real time(ioclass) with highest value(i.e 0). And for measurement of performance I have used the clock_gettime around io operations of threads.
But after running program I can't see the gain in execution time calling thread.
Following is the code
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<sys/syscall.h>
#include<unistd.h>
#include<time.h>
#define NB_THREADS 3
#define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | data)
#define IOPRIO_CLASS_SHIFT 13
#define BILLION 1000000000L
enum {
IOPRIO_CLASS_NONE,
IOPRIO_CLASS_RT,
IOPRIO_CLASS_BE,
IOPRIO_CLASS_IDLE,
};
enum {
IOPRIO_WHO_PROCESS = 1,
IOPRIO_WHO_PGRP,
IOPRIO_WHO_USER,
};
static inline int ioprio_set(int which, int who, int ioprio)
{
return syscall(SYS_ioprio_set, which, who, ioprio);
}
double times[NB_THREADS];
void *copyfile(void *args){
struct timespec start, stop;
double accum;
int x;
char finname[10];// name of the file to be copied
char foutname[10],ch;
int *id;
FILE *source, *target;
id = (int *) args;
sprintf(finname,"large%d.txt",*id);
sprintf(foutname,"out%d.txt",*id);
if(*id == 2){
x=ioprio_set(IOPRIO_WHO_PROCESS, 0, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_RT,0));
//printf("##%d##",x);
}
if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
perror( "clock gettime" );
exit(EXIT_FAILURE);
}
//printf("%s##%s\n\n",finname,foutname);
source = fopen(finname, "r");
if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
target = fopen(foutname, "w");
if( target == NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(source) ) != EOF )
{
fputc(ch, target);
}
//printf("\ndone copying file %s to %s in %lf\n",finname,foutname,accum);
fclose(source);
fclose(target);
if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
perror( "clock gettime" );
exit(EXIT_FAILURE);
}
accum = ( stop.tv_sec - start.tv_sec )
+ (double)( stop.tv_nsec - start.tv_nsec )
/ (double)BILLION;
times[*id]=accum;
}
int main()
{
unsigned int ints[NB_THREADS],i;
int err;
pthread_t threads[NB_THREADS];
for (i = 0; i < NB_THREADS; ++i) {
ints[i] = i;
err=pthread_create(&threads[i], NULL, copyfile , &ints[i]);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread %d created successfully\n",i);
//pthread_join(threads[i], NULL);
}
for (i = 0; i < NB_THREADS; ++i) {
pthread_join(threads[i], NULL);
}
for (i = 0; i < NB_THREADS; ++i) {
printf("\n %d : %lf",i,times[i]);
}
return 0;
}
Note : to call this api with IOPRIO_CLASS_RT, permissions are needed. (So already ran with sudo). ioprio_set is returning 0(successful call, it return -1 in case of failure).
Note : to compile this code add -lpthread and -lrt to gcc.
Q. Is some thing wrong with code structure.?
Q. How can I carry out this experiment correctly?
Q. What can be done to achieve desired thing i.e increasing i/o priority of thread over other threads?

Getting retval, cleanup, destroy failed using Papi

I am trying to test out using papi, but I am getting some errors that I don't understand why they're occurring. I couldn't find anything online for them. The code is below
I am using PAPI and C.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <memory.h>
#include <malloc.h>
#include "papi.h"
#define INDEX 100
static void test_fail(char *file, int line, char *call, int retval);
int main(int argc, char **argv) {
extern void dummy(void *);
float matrixa[INDEX][INDEX], matrixb[INDEX][INDEX], mresult[INDEX] [INDEX];
float real_time, proc_time, mflops;
long long flpins;
int retval, status = 0;
int i,j,k;
long_long values[1];
FILE *file;
file = fopen("output.txt","w");
retval = PAPI_library_init(PAPI_VER_CURRENT);
int EventSet = PAPI_NULL;
PAPI_create_eventset(&EventSet);
if(PAPI_add_event(EventSet, PAPI_LD_INS) != PAPI_OK)
{
fprintf(file,"PAPI failed to add Load/Store instructions\n");
}
if (PAPI_state(EventSet, &status) != PAPI_OK)
fprintf(file,"state fail\n");
fprintf(file, "State is now %d\n", status);
if (PAPI_start(EventSet) != PAPI_OK)
fprintf(file,"start fail\n");
if (PAPI_state(EventSet, &status) != PAPI_OK)
fprintf(file,"state2 fail\n");
fprintf(file, "State is now %d\n", status);
/* Initialize the Matrix arrays */
for ( i=0; i<INDEX; i++ ){
mresult[0][i] = 0.0;
matrixa[0][i] = matrixb[0][i] = rand()*(float)1.1; }
if((retval=PAPI_flops( &real_time, &proc_time, &flpins, &mflops))<PAPI_OK)
fprintf(file,"retval failed\n");
for (i=0;i<INDEX;i++)
{
for(j=0;j<INDEX;j++)
{
for(k=0;k<INDEX;k++)
{
mresult[i][j]=mresult[i][j] + matrixa[i][k]*matrixb[k][j];
}
}
}
if((retval=PAPI_flops( &real_time, &proc_time, &flpins, &mflops)) <PAPI_OK)
{
fprintf(infile,"ret2 failed\n");
}
fprintf(file,"Real_time:\t%f\nProc_time:\t%f\nTotal flpins:\t%lld \nMFLOPS:\t\t%f\n",
real_time, proc_time, flpins, mflops);
fflush(file);
fprintf(file,"%s\tPASSED\n", __FILE__);
fflush(file);
if (PAPI_read(EventSet, values) != PAPI_OK)
{fprintf(file,"read fail\n");}
if (PAPI_stop(EventSet, values) != PAPI_OK)
{fprintf(file,"stop fail\n");}
if (PAPI_cleanup_eventset(&EventSet) != PAPI_OK)
{fprintf(file,"cleanup fail\n");}
if (PAPI_destroy_eventset(&EventSet) != PAPI_OK)
{fprintf(file,"destroy fail\n");}
fprintf(file,"\nValues is %f\n", values[0]);
fflush(file);
fclose(file);
PAPI_shutdown();
exit(0);
}
In the output file, I just see the below:
State is now 1
State is now 2
retval failed
ret2 failed
Real_time: 0.000000
Proc_time: 0.000000
Total flpins: 99
MFLOPS: 0.000000
PAPI_flops.c PASSED
cleanup fail
destroy fail
I don't understand why ret, ret2, cleanup and destroy failed. Why?
You can use the PAPI_perror or PAPI_strerror functions to get the error message associated with an error return value. This may help track down why, for example, PAPI_flops is failing. (It could be that there is no support on your system for the required events.)
The reason why PAPI_cleanup_eventset is failing though is because it takes just the integer EventSet, not a pointer to it.
I'd strongly recommend emitting the error return value strings, and also compiling with warnings on — the latter would likely have found the issue with the wrong parameter type.

Resources